From c59ffebadb3cc6cc0f68496d03244bcea6c67274 Mon Sep 17 00:00:00 2001 From: nguyenanhung Date: Tue, 2 Apr 2024 18:46:39 +0700 Subject: [PATCH] Update v3.x --- README.md | 5 +- composer.json | 104 +- helpers/helpers.php | 108 +- src/CurlData.php | 1314 +++++++++--------- src/GetContents.php | 1390 +++++++++---------- src/Input.php | 864 ++++++------ src/MyRequests.php | 2712 +++++++++++++++++++------------------- src/ProjectInterface.php | 50 +- src/SoapRequest.php | 600 ++++----- src/Utils.php | 521 ++++---- src/Version.php | 24 +- test/functions.php | 70 +- test/testHelper.php | 10 +- test/testRequest.php | 14 +- test/testUtils.php | 2 +- 15 files changed, 3894 insertions(+), 3894 deletions(-) diff --git a/README.md b/README.md index 99d0dbe..1414fba 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Library use package: Curl, GuzzleHttp and nuSOAP - [x] V1.x, V2.x support all PHP version `>=5.6` - [x] V3.x support all PHP version `>=7.0` +- [x] V4.x support all PHP version `>=8.0` ## Installation @@ -26,7 +27,7 @@ unzip master.zip Step 2: Init to Project ```php -=7.0", - "ext-curl": "*", - "ext-json": "*", - "ext-iconv": "*", - "symfony/http-foundation": "^6.0 || ^5.3 || ^4.4 || ^3.4", - "symfony/polyfill-mbstring": ">= 1.0", - "php-curl-class/php-curl-class": "^9 || ^8", - "guzzlehttp/guzzle": "^7 || ^6", - "nguyenanhung/nusoap": "^0.9", - "nguyenanhung/my-debug": "^3.0 || ^2.0", - "nguyenanhung/ip-helper": "^2.0 || ^1.0" - }, - "require-dev": { - "kint-php/kint": "^5 || ^4 || ^3 || ^2 || ^1" - }, - "suggest": { - "ext-curl": "Needed to support cURL", - "ext-json": "Needed to support JSON", - "ext-iconv": "Needed to support iconv", - "ext-openssl": "Needed to support SSL", - "ext-mbstring": "Needed to support mb_string" - }, - "autoload": { - "psr-4": { - "nguyenanhung\\MyRequests\\": "src/" - }, - "files": [ - "helpers/helpers.php" - ] - } + "name": "nguyenanhung/requests", + "type": "library", + "description": "My Requests Library", + "keywords": [ + "request", + "http", + "curl", + "get_content", + "rest", + "soap" + ], + "homepage": "https://github.com/nguyenanhung/requests", + "license": "GPL-3.0", + "authors": [ + { + "name": "Nguyen An Hung", + "email": "dev@nguyenanhung.com", + "homepage": "https://nguyenanhung.com", + "role": "Developer" + } + ], + "require": { + "php": ">=7.0", + "ext-curl": "*", + "ext-json": "*", + "ext-iconv": "*", + "symfony/http-foundation": "^6.0 || ^5.3 || ^4.4 || ^3.4", + "symfony/polyfill-mbstring": ">= 1.0", + "php-curl-class/php-curl-class": "^9 || ^8", + "guzzlehttp/guzzle": "^7 || ^6", + "nguyenanhung/nusoap": "^0.9", + "nguyenanhung/my-debug": "^4.0 || ^3.0 || ^2.0", + "nguyenanhung/ip-helper": "^2.0 || ^1.0" + }, + "require-dev": { + "kint-php/kint": "^5 || ^4 || ^3 || ^2 || ^1" + }, + "suggest": { + "ext-curl": "Needed to support cURL", + "ext-json": "Needed to support JSON", + "ext-iconv": "Needed to support iconv", + "ext-openssl": "Needed to support SSL", + "ext-mbstring": "Needed to support mb_string" + }, + "autoload": { + "psr-4": { + "nguyenanhung\\MyRequests\\": "src/" + }, + "files": [ + "helpers/helpers.php" + ] + } } diff --git a/helpers/helpers.php b/helpers/helpers.php index 2f5b0fd..778f581 100644 --- a/helpers/helpers.php +++ b/helpers/helpers.php @@ -8,62 +8,62 @@ * Time: 23:16 */ if (!function_exists('sendSimpleRequest')) { - /** - * Function sendSimpleRequest - * - * @param string $url URL Target Endpoint - * @param string|array|object $data Array Data to Request - * @param string $method GET or POST - * - * @return bool|string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/03/2021 20:38 - */ - function sendSimpleRequest(string $url = '', $data = [], string $method = 'GET') - { - $target = (!empty($data) && (is_array($data) || is_object($data))) ? $url . '?' . http_build_query($data) : $url; - $method = mb_strtoupper($method); - $curl = curl_init(); - curl_setopt_array($curl, array( - CURLOPT_URL => $target, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_CUSTOMREQUEST => $method, - CURLOPT_POSTFIELDS => "", - CURLOPT_HTTPHEADER => array(), - )); - $response = curl_exec($curl); - $err = curl_error($curl); - curl_close($curl); - if ($err) { - $message = "cURL Error #: " . $err; - if (function_exists('log_message')) { - log_message('error', $message); - } + /** + * Function sendSimpleRequest + * + * @param string $url URL Target Endpoint + * @param string|array|object $data Array Data to Request + * @param string $method GET or POST + * + * @return bool|string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/03/2021 20:38 + */ + function sendSimpleRequest(string $url = '', $data = [], string $method = 'GET') + { + $target = (!empty($data) && (is_array($data) || is_object($data))) ? $url . '?' . http_build_query($data) : $url; + $method = mb_strtoupper($method); + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => $target, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_CUSTOMREQUEST => $method, + CURLOPT_POSTFIELDS => "", + CURLOPT_HTTPHEADER => array(), + )); + $response = curl_exec($curl); + $err = curl_error($curl); + curl_close($curl); + if ($err) { + $message = "cURL Error #: " . $err; + if (function_exists('log_message')) { + log_message('error', $message); + } - return null; - } + return null; + } - return $response; - } + return $response; + } } if (!function_exists('getIpAddress')) { - /** - * Function getIpAddress - * - * @param bool $convertToInteger - * - * @return bool|int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 10:36 - */ - function getIpAddress(bool $convertToInteger = false) - { - $ip = new nguyenanhung\MyRequests\Ip(); - return $ip->getIpAddress($convertToInteger); - } + /** + * Function getIpAddress + * + * @param bool $convertToInteger + * + * @return bool|int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 10:36 + */ + function getIpAddress(bool $convertToInteger = false) + { + $ip = new nguyenanhung\MyRequests\Ip(); + return $ip->getIpAddress($convertToInteger); + } } diff --git a/src/CurlData.php b/src/CurlData.php index e964e82..b8ee741 100644 --- a/src/CurlData.php +++ b/src/CurlData.php @@ -18,661 +18,661 @@ */ class CurlData { - /** @var bool Set Authentication */ - protected $authentication = false; - /** @var string Username */ - protected $username = ''; - /** @var string Password */ - protected $password = ''; - /** @var string URL */ - protected $url; - /** @var null|array|string Data to Send Request */ - protected $data; - /** @var int Timeout to Request */ - protected $timeout; - /** @var bool Set is POST */ - protected $isPost; - /** @var bool Set is JSON */ - protected $isJson; - /** @var bool Set is XML */ - protected $isXML; - /** @var string User Agent */ - protected $userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'; - /** @var string Cookie File Location */ - protected $cookieFileLocation; - /** @var bool Set Follow Location */ - protected $followLocation; - /** @var int Set Max Redirect */ - protected $maxRedirect; - /** @var string Referer URL */ - protected $referer; - /** @var null|array|string Session Data */ - protected $session; - /** @var bool Include Header */ - protected $includeHeader; - /** @var bool NoBody */ - protected $noBody; - /** @var bool Binary Transfer */ - protected $binaryTransfer; - public $status; - public $response; - public $request_headers; - public $response_headers; - public $curl_error; - public $curl_error_code; - public $curl_error_message; - public $http_error; - public $http_status_code; - public $http_error_message; - public $error; - public $error_code; - public $error_message; - - /** - * CurlData constructor. - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function __construct() - { - } - - /** - * Function __toString - * - * @return mixed - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 56:23 - */ - public function __toString() - { - return $this->response; - } - - /** - * Function setAuthentication - * - * @param false $authentication - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 16:42 - */ - public function setAuthentication(bool $authentication = false): self - { - $this->authentication = $authentication; - - return $this; - } - - /** - * Function getAuthentication - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:08 - */ - public function getAuthentication(): bool - { - return $this->authentication; - } - - /** - * Function setUsername - * - * @param string $username - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:11 - */ - public function setUsername(string $username = ''): self - { - $this->username = $username; - - return $this; - } - - /** - * Function getUsername - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:19 - */ - public function getUsername(): string - { - return $this->username; - } - - /** - * Function setPassword - * - * @param string $password - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:25 - */ - public function setPassword(string $password = ''): self - { - $this->password = $password; - - return $this; - } - - /** - * Function getPassword - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:29 - */ - public function getPassword(): string - { - return $this->password; - } - - /** - * Function setUrl - * - * @param string $url - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:32 - */ - public function setUrl(string $url = ''): self - { - $this->url = $url; - - return $this; - } - - /** - * Function getUrl - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:35 - */ - public function getUrl(): string - { - return $this->url; - } - - /** - * Function setData - * - * @param array|mixed $data - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:38 - */ - public function setData($data = array()): self - { - $this->data = $data; - - return $this; - } - - /** - * Function getData - * - * @return array|string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:42 - */ - public function getData() - { - return $this->data; - } - - /** - * Function setTimeout - * - * @param int $timeout - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:45 - */ - public function setTimeout(int $timeout = 60): self - { - $this->timeout = $timeout; - - return $this; - } - - /** - * Function getTimeout - * - * @return int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:47 - */ - public function getTimeout(): int - { - return $this->timeout; - } - - /** - * Function isPost - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 54:51 - */ - public function isPost(): self - { - $this->isPost = true; - - return $this; - } - - /** - * Function isJson - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:02 - */ - public function isJson(): self - { - $this->isJson = true; - - return $this; - } - - /** - * Function isXML - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:05 - */ - public function isXML(): self - { - $this->isXML = true; - - return $this; - } - - /** - * Function setUserAgent - * - * @param string $userAgent - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:09 - */ - public function setUserAgent(string $userAgent = ''): self - { - $this->userAgent = $userAgent; - - return $this; - } - - /** - * Function getUserAgent - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:12 - */ - public function getUserAgent(): string - { - return $this->userAgent; - } - - /** - * Function setCookieFileLocation - * - * @param string $cookieFileLocation - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:15 - */ - public function setCookieFileLocation(string $cookieFileLocation = ''): self - { - $this->cookieFileLocation = $cookieFileLocation; - - return $this; - } - - /** - * Function getCookieFileLocation - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:18 - */ - public function getCookieFileLocation(): string - { - return $this->cookieFileLocation; - } - - /** - * Function setFollowLocation - * - * @param bool $followLocation - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:21 - */ - public function setFollowLocation(bool $followLocation = true): self - { - $this->followLocation = $followLocation; - - return $this; - } - - /** - * Function getFollowLocation - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:25 - */ - public function getFollowLocation(): bool - { - return $this->followLocation; - } - - /** - * Function setMaxRedirect - * - * @param int $maxRedirect - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:29 - */ - public function setMaxRedirect(int $maxRedirect = 10): self - { - $this->maxRedirect = $maxRedirect; - - return $this; - } - - /** - * Function getMaxRedirect - * - * @return int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:34 - */ - public function getMaxRedirect(): int - { - return $this->maxRedirect; - } - - /** - * Function setReferer - * - * @param string $referer - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:38 - */ - public function setReferer(string $referer = ''): self - { - $this->referer = $referer; - - return $this; - } - - /** - * Function getReferer - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:42 - */ - public function getReferer(): string - { - return $this->referer; - } - - /** - * Function setSession - * - * @param array|mixed $session - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:44 - */ - public function setSession($session = array()): self - { - $this->session = $session; - - return $this; - } - - /** - * Function getSession - * - * @return array|string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:47 - */ - public function getSession() - { - return $this->session; - } - - /** - * Function setIncludeHeader - * - * @param bool $includeHeader - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:51 - */ - public function setIncludeHeader(bool $includeHeader = true): self - { - $this->includeHeader = $includeHeader; - - return $this; - } - - /** - * Function getIncludeHeader - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 55:57 - */ - public function getIncludeHeader(): bool - { - return $this->includeHeader; - } - - /** - * Function setBinaryTransfer - * - * @param bool $binaryTransfer - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 56:00 - */ - public function setBinaryTransfer(bool $binaryTransfer = true): self - { - $this->binaryTransfer = $binaryTransfer; - - return $this; - } - - /** - * Function isBinaryTransfer - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 56:03 - */ - public function isBinaryTransfer(): bool - { - return $this->binaryTransfer; - } - - /** - * Function setNoBody - * - * @param bool $noBody - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 56:10 - */ - public function setNoBody(bool $noBody = true): self - { - $this->noBody = $noBody; - - return $this; - } - - /** - * Function getNoBody - * - * @return bool - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 56:14 - */ - public function getNoBody(): bool - { - return $this->noBody; - } - - /** - * Function createCurl - * - * @param string $url - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 56:20 - */ - public function createCurl(string $url = ''): self - { - if (!empty($url)) { - $this->url = $url; - } - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, $this->url); - curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); - curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); - curl_setopt($curl, CURLOPT_MAXREDIRS, $this->maxRedirect); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $this->followLocation); - curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookieFileLocation); - curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookieFileLocation); - if ($this->authentication) { - curl_setopt($curl, CURLOPT_USERPWD, $this->username . ':' . $this->password); - } - if ($this->includeHeader) { - curl_setopt($curl, CURLOPT_HEADER, true); - } - if ($this->isPost) { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data); - } - if ($this->isJson) { - $header[] = 'Accept: application/json'; - curl_setopt($curl, CURLOPT_HEADER, $header[]); - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($this->data)); - } - if ($this->isXML) { - $header[] = 'Accept: text/xml'; - curl_setopt($curl, CURLOPT_HEADER, $header[]); - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data); - } - if ($this->noBody) { - curl_setopt($curl, CURLOPT_NOBODY, true); - } - if ($this->referer) { - curl_setopt($curl, CURLOPT_REFERER, $this->referer); - } - curl_setopt($curl, CURLOPT_USERAGENT, $this->userAgent); - $parseUrl = parse_url($url); - if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'https') { - curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); - } - if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'http') { - curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); - } - $this->response_headers = array(); - $this->response = curl_exec($curl); - $this->status = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $this->curl_error_code = curl_errno($curl); - $this->curl_error_message = curl_error($curl); - $this->curl_error = !($this->curl_error_code === 0); - $this->http_status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $this->http_error = in_array(floor($this->http_status_code / 100), array(4, 5), true); - $this->error = $this->curl_error || $this->http_error; - $this->error_code = $this->error ? ($this->curl_error ? $this->curl_error_code : $this->http_status_code) : 0; - $this->request_headers = preg_split('/\r\n/', curl_getinfo($curl, CURLINFO_HEADER_OUT), null, PREG_SPLIT_NO_EMPTY); - if (isset($this->response_headers['0'])) { - if ($this->error) { - $this->http_error_message = ($this->response_headers['0']); - } else { - $this->http_error_message = ''; - } - } else { - if ($this->error) { - $this->http_error_message = (''); - } else { - $this->http_error_message = ''; - } - } - $this->error_message = $this->curl_error ? $this->curl_error_message : $this->http_error_message; - curl_close($curl); - - return $this; - } + /** @var bool Set Authentication */ + protected $authentication = false; + /** @var string Username */ + protected $username = ''; + /** @var string Password */ + protected $password = ''; + /** @var string URL */ + protected $url; + /** @var null|array|string Data to Send Request */ + protected $data; + /** @var int Timeout to Request */ + protected $timeout; + /** @var bool Set is POST */ + protected $isPost; + /** @var bool Set is JSON */ + protected $isJson; + /** @var bool Set is XML */ + protected $isXML; + /** @var string User Agent */ + protected $userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'; + /** @var string Cookie File Location */ + protected $cookieFileLocation; + /** @var bool Set Follow Location */ + protected $followLocation; + /** @var int Set Max Redirect */ + protected $maxRedirect; + /** @var string Referer URL */ + protected $referer; + /** @var null|array|string Session Data */ + protected $session; + /** @var bool Include Header */ + protected $includeHeader; + /** @var bool NoBody */ + protected $noBody; + /** @var bool Binary Transfer */ + protected $binaryTransfer; + public $status; + public $response; + public $request_headers; + public $response_headers; + public $curl_error; + public $curl_error_code; + public $curl_error_message; + public $http_error; + public $http_status_code; + public $http_error_message; + public $error; + public $error_code; + public $error_message; + + /** + * CurlData constructor. + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function __construct() + { + } + + /** + * Function __toString + * + * @return mixed + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 56:23 + */ + public function __toString() + { + return $this->response; + } + + /** + * Function setAuthentication + * + * @param false $authentication + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 16:42 + */ + public function setAuthentication(bool $authentication = false): self + { + $this->authentication = $authentication; + + return $this; + } + + /** + * Function getAuthentication + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:08 + */ + public function getAuthentication(): bool + { + return $this->authentication; + } + + /** + * Function setUsername + * + * @param string $username + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:11 + */ + public function setUsername(string $username = ''): self + { + $this->username = $username; + + return $this; + } + + /** + * Function getUsername + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:19 + */ + public function getUsername(): string + { + return $this->username; + } + + /** + * Function setPassword + * + * @param string $password + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:25 + */ + public function setPassword(string $password = ''): self + { + $this->password = $password; + + return $this; + } + + /** + * Function getPassword + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:29 + */ + public function getPassword(): string + { + return $this->password; + } + + /** + * Function setUrl + * + * @param string $url + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:32 + */ + public function setUrl(string $url = ''): self + { + $this->url = $url; + + return $this; + } + + /** + * Function getUrl + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:35 + */ + public function getUrl(): string + { + return $this->url; + } + + /** + * Function setData + * + * @param array|mixed $data + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:38 + */ + public function setData($data = array()): self + { + $this->data = $data; + + return $this; + } + + /** + * Function getData + * + * @return array|string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:42 + */ + public function getData() + { + return $this->data; + } + + /** + * Function setTimeout + * + * @param int $timeout + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:45 + */ + public function setTimeout(int $timeout = 60): self + { + $this->timeout = $timeout; + + return $this; + } + + /** + * Function getTimeout + * + * @return int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:47 + */ + public function getTimeout(): int + { + return $this->timeout; + } + + /** + * Function isPost + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 54:51 + */ + public function isPost(): self + { + $this->isPost = true; + + return $this; + } + + /** + * Function isJson + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:02 + */ + public function isJson(): self + { + $this->isJson = true; + + return $this; + } + + /** + * Function isXML + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:05 + */ + public function isXML(): self + { + $this->isXML = true; + + return $this; + } + + /** + * Function setUserAgent + * + * @param string $userAgent + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:09 + */ + public function setUserAgent(string $userAgent = ''): self + { + $this->userAgent = $userAgent; + + return $this; + } + + /** + * Function getUserAgent + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:12 + */ + public function getUserAgent(): string + { + return $this->userAgent; + } + + /** + * Function setCookieFileLocation + * + * @param string $cookieFileLocation + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:15 + */ + public function setCookieFileLocation(string $cookieFileLocation = ''): self + { + $this->cookieFileLocation = $cookieFileLocation; + + return $this; + } + + /** + * Function getCookieFileLocation + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:18 + */ + public function getCookieFileLocation(): string + { + return $this->cookieFileLocation; + } + + /** + * Function setFollowLocation + * + * @param bool $followLocation + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:21 + */ + public function setFollowLocation(bool $followLocation = true): self + { + $this->followLocation = $followLocation; + + return $this; + } + + /** + * Function getFollowLocation + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:25 + */ + public function getFollowLocation(): bool + { + return $this->followLocation; + } + + /** + * Function setMaxRedirect + * + * @param int $maxRedirect + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:29 + */ + public function setMaxRedirect(int $maxRedirect = 10): self + { + $this->maxRedirect = $maxRedirect; + + return $this; + } + + /** + * Function getMaxRedirect + * + * @return int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:34 + */ + public function getMaxRedirect(): int + { + return $this->maxRedirect; + } + + /** + * Function setReferer + * + * @param string $referer + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:38 + */ + public function setReferer(string $referer = ''): self + { + $this->referer = $referer; + + return $this; + } + + /** + * Function getReferer + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:42 + */ + public function getReferer(): string + { + return $this->referer; + } + + /** + * Function setSession + * + * @param array|mixed $session + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:44 + */ + public function setSession($session = array()): self + { + $this->session = $session; + + return $this; + } + + /** + * Function getSession + * + * @return array|string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:47 + */ + public function getSession() + { + return $this->session; + } + + /** + * Function setIncludeHeader + * + * @param bool $includeHeader + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:51 + */ + public function setIncludeHeader(bool $includeHeader = true): self + { + $this->includeHeader = $includeHeader; + + return $this; + } + + /** + * Function getIncludeHeader + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 55:57 + */ + public function getIncludeHeader(): bool + { + return $this->includeHeader; + } + + /** + * Function setBinaryTransfer + * + * @param bool $binaryTransfer + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 56:00 + */ + public function setBinaryTransfer(bool $binaryTransfer = true): self + { + $this->binaryTransfer = $binaryTransfer; + + return $this; + } + + /** + * Function isBinaryTransfer + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 56:03 + */ + public function isBinaryTransfer(): bool + { + return $this->binaryTransfer; + } + + /** + * Function setNoBody + * + * @param bool $noBody + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 56:10 + */ + public function setNoBody(bool $noBody = true): self + { + $this->noBody = $noBody; + + return $this; + } + + /** + * Function getNoBody + * + * @return bool + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 56:14 + */ + public function getNoBody(): bool + { + return $this->noBody; + } + + /** + * Function createCurl + * + * @param string $url + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 56:20 + */ + public function createCurl(string $url = ''): self + { + if (!empty($url)) { + $this->url = $url; + } + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $this->url); + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); + curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); + curl_setopt($curl, CURLOPT_MAXREDIRS, $this->maxRedirect); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $this->followLocation); + curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookieFileLocation); + curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookieFileLocation); + if ($this->authentication) { + curl_setopt($curl, CURLOPT_USERPWD, $this->username . ':' . $this->password); + } + if ($this->includeHeader) { + curl_setopt($curl, CURLOPT_HEADER, true); + } + if ($this->isPost) { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data); + } + if ($this->isJson) { + $header[] = 'Accept: application/json'; + curl_setopt($curl, CURLOPT_HEADER, $header[]); + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($this->data)); + } + if ($this->isXML) { + $header[] = 'Accept: text/xml'; + curl_setopt($curl, CURLOPT_HEADER, $header[]); + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data); + } + if ($this->noBody) { + curl_setopt($curl, CURLOPT_NOBODY, true); + } + if ($this->referer) { + curl_setopt($curl, CURLOPT_REFERER, $this->referer); + } + curl_setopt($curl, CURLOPT_USERAGENT, $this->userAgent); + $parseUrl = parse_url($url); + if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'https') { + curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); + } + if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'http') { + curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); + } + $this->response_headers = array(); + $this->response = curl_exec($curl); + $this->status = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $this->curl_error_code = curl_errno($curl); + $this->curl_error_message = curl_error($curl); + $this->curl_error = !($this->curl_error_code === 0); + $this->http_status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $this->http_error = in_array(floor($this->http_status_code / 100), array(4, 5), true); + $this->error = $this->curl_error || $this->http_error; + $this->error_code = $this->error ? ($this->curl_error ? $this->curl_error_code : $this->http_status_code) : 0; + $this->request_headers = preg_split('/\r\n/', curl_getinfo($curl, CURLINFO_HEADER_OUT), null, PREG_SPLIT_NO_EMPTY); + if (isset($this->response_headers['0'])) { + if ($this->error) { + $this->http_error_message = ($this->response_headers['0']); + } else { + $this->http_error_message = ''; + } + } else { + if ($this->error) { + $this->http_error_message = (''); + } else { + $this->http_error_message = ''; + } + } + $this->error_message = $this->curl_error ? $this->curl_error_message : $this->http_error_message; + curl_close($curl); + + return $this; + } } diff --git a/src/GetContents.php b/src/GetContents.php index e4aca0b..c014a0d 100644 --- a/src/GetContents.php +++ b/src/GetContents.php @@ -22,699 +22,699 @@ */ class GetContents implements ProjectInterface { - use Version; - - /** @var object \nguyenanhung\MyDebug\Benchmark */ - private $benchmark; - - /** @var object \nguyenanhung\MyDebug\Debug */ - private $logger; - - /** @var bool Set Debug Status */ - public $debugStatus = false; - - /** @var null|string Set level Debug: DEBUG, INFO, ERROR .... */ - public $debugLevel = 'error'; - - /** @var string Set Logger Path to Save */ - public $debugLoggerPath = ''; - - /** @var string|null Set Logger Filename to Save */ - public $debugLoggerFilename = ''; - - /** @var null|array|object|mixed Response from Request */ - private $response; - - /** @var string The base URL to be the target of the Request */ - private $url = ''; - - /** @var string The method to use - GET, POST, PUT, DELETE */ - private $method = 'GET'; - - /** @var array An array of headers to be added to the request */ - private $headers = array(); - - /** @var array An array of cookies (which are added to the headers) */ - private $cookies = array(); - - /** @var array An array of data to be added to the request. Where the method is POST these are sent as a form body, otherwise - they are added as a query string */ - private $data = array(); - - /** @var array An array of items to be sent as a query string */ - private $query_string = array(); - - /** @var bool|mixed Should we track cookies? This does not stop the processing of cookies, it just allows for any received cookies to be sent in subsequent requests. Great for scraping. */ - private $trackCookies = true; - - /** @var bool Is the request sent in XML and received in XML */ - private $isXML = false; - - /** @var bool Is the request sent in JSON and received in JSON */ - private $isJson = false; - - /** @var bool Is the response decode Json to Object */ - private $isDecodeJson = false; - - /** @var bool Should JSON be sent in JSON_PRETTY_PRINT? Only really useful for debugging. */ - private $isJsonPretty = false; - - /** @var bool|mixed Should SSL peers be verified. You should have a good reason for turning this off. */ - private $verifyPeer = true; - - /** @var int How long to wait for a server to respond to a request. */ - private $timeout = 60; - - /** @var bool Internal flag to track if the request is in SSL or not. */ - private $isSSL = false; - - /** - * GetContents constructor. - * - * @param string $url Url Endpoint - * @param string $method The method to use - GET, POST, PUT, DELETE - * @param array $data An array of data to be added to the request. - * Where the method is POST these are sent as a form body, - * otherwise - they are added as a query string - * @param array $headers An array of headers to be added to the request - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function __construct(string $url = '', string $method = 'GET', array $data = array(), array $headers = array()) - { - if (self::USE_BENCHMARK === true) { - $this->benchmark = new Benchmark(); - $this->benchmark->mark('code_start'); - } - $this->logger = new Logger(); - if (empty($this->debugLoggerPath)) { - $this->debugStatus = false; - } - $this->logger->setDebugStatus($this->debugStatus); - $this->logger->setGlobalLoggerLevel($this->debugLevel); - $this->logger->setLoggerPath($this->debugLoggerPath); - $this->logger->setLoggerSubPath(__CLASS__); - if (empty($this->debugLoggerFilename)) { - $this->debugLoggerFilename = 'Log-' . date('Y-m-d') . '.log'; - } - $this->logger->setLoggerFilename($this->debugLoggerFilename); - if ($url) { - $this->setURL($url); // If $url is not Empty, call method setURL - } - $this->setMethod($method); - $this->setData($data); - $this->setHeaders($headers); - } - - /** - * GetContents destructor. - */ - public function __destruct() - { - if (self::USE_BENCHMARK === true) { - $this->benchmark->mark('code_end'); - $this->logger->debug(__FUNCTION__, 'Elapsed Time: ===> ' . $this->benchmark->elapsed_time('code_start', 'code_end')); - $this->logger->debug(__FUNCTION__, 'Memory Usage: ===> ' . $this->benchmark->memory_usage()); - } - } - - /** - * Function getContent - Get Body Content from Request - * - * @return array|mixed|object|string|null Return Response content if exists - * Full Response content if $this->response['content'] not exists - * Exception Error Message if Exception Error - * Null if Not - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/7/18 02:08 - */ - public function getContent() - { - try { - if ($this->response) { - return $this->response['content'] ?? $this->response; - } - } catch (Exception $e) { - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - - return $e->getMessage(); - } - - return null; - } - - /** - * Function getError - Get Error Code and Message - * - * @return array|mixed|object|string|null Return Response error if exists - * Full Response if $this->response['error'] not exists - * Exception Error Message if Exception Error - * Null if Not - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/9/18 09:33 - */ - public function getError() - { - try { - if ($this->response) { - return $this->response['error'] ?? $this->response; - } - } catch (Exception $e) { - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - - return $e->getMessage(); - } - - return null; - } - - /** - * Function get Response of Request - * - * @return array|mixed|object|null Array if Exists, Null if Not Response - * @author: 713uk13m - * @time : 10/7/18 01:50 - */ - public function response() - { - if ($this->response) { - return $this->response; - } - - return null; - } - - /** - * Let's go to Request - * - * @return array|null|string Response from Request if Exists - * Exception Error Message if Exception Error - * Null if Not - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:12 - */ - public function sendRequest() - { - try { - if (mb_strlen($this->url) >= 9) { - $response = $this->useFileGetContents(); - $this->response = $response; - - return $response; - } - } catch (Exception $e) { - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - - return $e->getMessage(); - } - - return null; - } - - /** - * Function useFileGetContents. Use file_get_contents to perform the request - * - * @return array The server response array - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:19 - */ - public function useFileGetContents(): array - { - $return = array(); - - // Options Setup - $options = array( - 'http' => array( - 'method' => $this->method, - 'timeout' => $this->timeout - ) - ); - - // Use SSL - if ($this->isSSL) { - $options['ssl'] = array( - 'verify_peer' => $this->verifyPeer, - 'verify_peer_name' => $this->verifyPeer - ); - } - - $headers = $this->getHeaderArray(); - - if (count($headers) > 0) { - $options['http']['header'] = implode("\r\n", $headers); - } - - if ($this->method === 'POST') { - $post = $this->getPostBody(); - if ($post !== '') { - $options['http']['content'] = $post; - } - $return['post'] = $post; - } - - $context = stream_context_create($options); - $query_string = $this->getQueryString(); - $this->logger->debug(__FUNCTION__, 'Options into Request: ', $options); - $this->logger->debug(__FUNCTION__, 'Data Query String into Request: ', $query_string); - $this->logger->debug(__FUNCTION__, 'Endpoint URL into Request: ', $this->url); - try { - $response = file_get_contents($this->url . $query_string, false, $context); - $responseHeaders = $http_response_header; - $return['headers'] = $this->parseReturnHeaders($responseHeaders); - $return['url'] = $this->url . $query_string; - if ($response) { - $return['content'] = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($response)); - if ($this->isJson === true && $this->isDecodeJson === true) { - $responseJson = json_decode(trim($return['content'])); - if (json_last_error() === JSON_ERROR_NONE) { - $return['content'] = $responseJson; - $this->logger->debug(__FUNCTION__, 'Set Response is Json: ', $return['content']); - } - } - } - } catch (Exception $e) { - $return['error'] = array( - 'code' => 500, - 'message' => 'Could not file_get_contents.', - 'extended' => $e - ); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - } - - if (isset($return['headers']['response_code'])) { - $responseType = mb_substr($return['headers']['response_code'], 0, 1); - if ($responseType !== '2') { - $return['error'] = array( - 'code' => $return['headers']['response_code'], - 'message' => 'Server returned an error.' - ); - $this->logger->error(__FUNCTION__, 'Could not file_get_contents: ', $return['error']); - } - } - - $cookies = array(); - foreach ($http_response_header as $hdr) { - if (preg_match('/^Set-Cookie:\s*([^;]+)/i', $hdr, $matches)) { - parse_str($matches[1], $tmp); - $cookies += $tmp; - } - } - - if ($this->trackCookies) { - $cookies = array_merge($this->cookies, $cookies); - $this->cookies = $cookies; - } - $return['cookies'] = $cookies; - $this->logger->info(__FUNCTION__, 'Final Result from Server: ', $return); - - return $return; - } - - /** - * Generate the complete header array. Merges the supplied (if any) headers with those needed by the request. - * - * @return array An array of headers - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:19 - */ - public function getHeaderArray(): array - { - $headerArray = (count($this->headers) > 0 ? $this->headers : []); - if ($this->isJson) { - $headerArray[] = 'Accept: application/json'; - } - if ($this->isXML) { - $headerArray[] = 'Accept: text/xml'; - } - if ($this->isJson && $this->method === 'POST' && count($this->data) > 0) { - $headerArray[] = 'Content-type: application/json'; - } elseif ($this->isXML && $this->method === 'POST' && count($this->data) > 0) { - $headerArray[] = 'Content-type: text/xml'; - } elseif ($this->method === 'POST' && count($this->data) > 0) { - $headerArray[] = 'Content-type: application/x-www-form-urlencoded'; - } - if (count($this->cookies) > 0) { - $cookies = ''; - foreach ($this->cookies as $key => $value) { - if ($cookies !== '') { - $cookies .= '; '; - } - $cookies .= urlencode($key) . '=' . urlencode($value); - } - $headerArray[] = 'Cookie: ' . $cookies; - } - - return $headerArray; - } - - /** - * Get the post body - either JSON encoded or ready to be sent as a form post - * - * @return array|false|string Data to be sent Request - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:19 - */ - public function getPostBody() - { - $output = ''; - if ($this->isJson) { - $jsonPretty = ($this->isJsonPretty ? JSON_PRETTY_PRINT : null); - if (count($this->data) > 0) { - $output = json_encode($this->data, $jsonPretty); - } - } elseif ($this->isXML) { - $output = $this->data; - } elseif (count($this->data) > 0) { - $output = http_build_query($this->data); - } - - return $output; - } - - /** - * Get the query string by merging any supplied string with that of the generated components. - * - * @return string The query string - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:19 - */ - public function getQueryString(): string - { - $query_string = ''; - if (count($this->query_string) > 0) { - $query_string .= http_build_query($this->query_string); - } - if (($this->method !== 'POST') && count($this->data) > 0) { - $query_string .= http_build_query($this->data); - } - if ($query_string !== '') { - $query_string = (mb_strpos($this->url, '?') ? '&' : '?') . $query_string; - } - - return $query_string; - } - - /** - * Set the target URL - Must include http:// or https:// - * - * @param string $url - * - * @return $this - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:10 - */ - public function setURL(string $url = ''): self - { - try { - if ($url !== '') { - if (mb_strpos($url, 'https://') === 0) { - $this->isSSL = true; - $this->logger->debug(__FUNCTION__, 'Set SSL: ' . $this->isSSL); - } elseif (mb_strpos($url, 'http://') === 0) { - $this->isSSL = true; - $this->logger->debug(__FUNCTION__, 'Set SSL: ' . $this->isSSL); - } - } - $this->url = $url; - } catch (Exception $e) { - $this->url = null; - $message = "Error: " . __CLASS__ . ": Invalid protocol specified. URL must start with http:// or https:// - " . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage(); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $message); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - } - $this->logger->debug(__FUNCTION__, 'Endpoint URL to Request: ', $this->url); - - return $this; - } - - /** - * Set the HTTP method: GET, HEAD, PUT, POST, DELETE are valid - * - * @param string $method Method to Request GET, HEAD, PUT, POST, DELETE are valid - * - * @return $this|string Method - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:15 - */ - public function setMethod(string $method = '') - { - if ($method === '') { - $this->logger->debug(__FUNCTION__, 'Set Default Method = GET if $method is does not exist'); - $method = 'GET'; - } else { - $method = mb_strtoupper($method); - $validMethods = array('GET', 'HEAD', 'PUT', 'POST', 'DELETE'); - if (!in_array($method, $validMethods)) { - $message = "Error: " . __CLASS__ . ": The requested method (" . $method . ") is not valid here"; - $this->logger->error(__FUNCTION__, $message); - - return $message; - } - } - $this->method = $method; - - return $this; - } - - /** - * Set Data contents. Must be supplied as an array - * - * @param array|string $inputData The contents to be sent to the target URL - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:18 - */ - public function setData($inputData = array()) - { - if (is_string($inputData)) { - parse_str($inputData, $data); - } else { - $data = $inputData; - } - - if (count($data) === 0) { - $this->data = array(); - } else { - $this->data = $data; - } - $this->logger->debug(__FUNCTION__, 'Data into Request: ', $this->data); - } - - /** - * Set query string data. Must be supplied as an array - * - * @param array|string $inputQueryString The query string to be sent to the target URL - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 01:36 - */ - public function setQueryString($inputQueryString = array()) - { - if (is_string($inputQueryString)) { - parse_str($inputQueryString, $queryString); - } else { - $queryString = $inputQueryString; - } - if (count($queryString) === 0) { - $this->query_string = array(); - } else { - $this->query_string = $queryString; - } - } - - /** - * Set any headers to be sent to the target URL. Must be supplied as an array - * - * @param array $headers Header to Set - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:18 - */ - public function setHeaders(array $headers = array()) - { - if (!is_array($headers)) { - $this->headers = array(); - } else { - $this->headers = $headers; - } - } - - /** - * Set any cookies to be included in the headers. Must be supplied as an array - * - * @param array $cookies The array of cookies to be sent - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:18 - */ - public function setCookies(array $cookies = array()) - { - if (!is_array($cookies)) { - $this->cookies = array(); - } else { - $this->cookies = $cookies; - $this->trackCookies = true; - } - } - - /** - * Should cookies be tracked? - * - * @param boolean $value true to track cookies - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:18 - */ - public function setTrackCookies(bool $value = false) - { - if (!$value) { - $this->trackCookies = false; - } else { - $this->trackCookies = true; - } - } - - /** - * Function setXML - Is this transaction sending / expecting XML - * - * @param bool $value true if XML is being used and is expected - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 01:38 - */ - public function setXML(bool $value = false) - { - if (!$value) { - $this->isXML = false; - } else { - $this->isXML = true; - } - } - - /** - * Is this transaction sending / expecting JSON - * - * @param boolean $value true if JSON is being used and is expected - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:17 - */ - public function setJson(bool $value = false) - { - if (!$value) { - $this->isJson = false; - } else { - $this->isJson = true; - } - } - - /** - * Should JSON being sent be encoded in an easily readable format? Only useful for debugging - * - * @param boolean $value true for JSON_PRETTY_PRINT - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:17 - */ - public function setJsonPretty(bool $value = false) - { - if (!$value) { - $this->isJsonPretty = false; - } else { - $this->isJsonPretty = true; - } - } - - /** - * Should SSL peers be verified? - * - * @param bool $value - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:17 - */ - public function setVerifyPeer(bool $value = false) - { - if (!$value) { - $this->verifyPeer = false; - } else { - $this->verifyPeer = true; - } - } - - /** - * Function setTimeout - * - * @param int $timeout - * - * @example 60 - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:17 - */ - public function setTimeout(int $timeout = 20) - { - $this->timeout = $timeout; - } - - /** - * Parse HTTP response headers - * - * @param array $headers - * - * @return array Header Response - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 02:17 - */ - public function parseReturnHeaders(array $headers): array - { - $head = array(); - foreach ($headers as $value) { - $t = explode(':', $value, 2); - if (isset($t[1])) { - $head[trim($t[0])] = trim($t[1]); - } else { - $head[] = $value; - $patternHttp = "#HTTP/[0-9\.]+\s+([0-9]+)#"; - if (preg_match($patternHttp, $value, $out)) { - $head['response_code'] = (int) $out[1]; - } - } - } - $this->logger->debug(__FUNCTION__, 'Response Header: ', $head); - - return $head; - } + use Version; + + /** @var object \nguyenanhung\MyDebug\Benchmark */ + private $benchmark; + + /** @var object \nguyenanhung\MyDebug\Debug */ + private $logger; + + /** @var bool Set Debug Status */ + public $debugStatus = false; + + /** @var null|string Set level Debug: DEBUG, INFO, ERROR .... */ + public $debugLevel = 'error'; + + /** @var string Set Logger Path to Save */ + public $debugLoggerPath = ''; + + /** @var string|null Set Logger Filename to Save */ + public $debugLoggerFilename = ''; + + /** @var null|array|object|mixed Response from Request */ + private $response; + + /** @var string The base URL to be the target of the Request */ + private $url = ''; + + /** @var string The method to use - GET, POST, PUT, DELETE */ + private $method = 'GET'; + + /** @var array An array of headers to be added to the request */ + private $headers = array(); + + /** @var array An array of cookies (which are added to the headers) */ + private $cookies = array(); + + /** @var array An array of data to be added to the request. Where the method is POST these are sent as a form body, otherwise - they are added as a query string */ + private $data = array(); + + /** @var array An array of items to be sent as a query string */ + private $query_string = array(); + + /** @var bool|mixed Should we track cookies? This does not stop the processing of cookies, it just allows for any received cookies to be sent in subsequent requests. Great for scraping. */ + private $trackCookies = true; + + /** @var bool Is the request sent in XML and received in XML */ + private $isXML = false; + + /** @var bool Is the request sent in JSON and received in JSON */ + private $isJson = false; + + /** @var bool Is the response decode Json to Object */ + private $isDecodeJson = false; + + /** @var bool Should JSON be sent in JSON_PRETTY_PRINT? Only really useful for debugging. */ + private $isJsonPretty = false; + + /** @var bool|mixed Should SSL peers be verified. You should have a good reason for turning this off. */ + private $verifyPeer = true; + + /** @var int How long to wait for a server to respond to a request. */ + private $timeout = 60; + + /** @var bool Internal flag to track if the request is in SSL or not. */ + private $isSSL = false; + + /** + * GetContents constructor. + * + * @param string $url Url Endpoint + * @param string $method The method to use - GET, POST, PUT, DELETE + * @param array $data An array of data to be added to the request. + * Where the method is POST these are sent as a form body, + * otherwise - they are added as a query string + * @param array $headers An array of headers to be added to the request + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function __construct(string $url = '', string $method = 'GET', array $data = array(), array $headers = array()) + { + if (self::USE_BENCHMARK === true) { + $this->benchmark = new Benchmark(); + $this->benchmark->mark('code_start'); + } + $this->logger = new Logger(); + if (empty($this->debugLoggerPath)) { + $this->debugStatus = false; + } + $this->logger->setDebugStatus($this->debugStatus); + $this->logger->setGlobalLoggerLevel($this->debugLevel); + $this->logger->setLoggerPath($this->debugLoggerPath); + $this->logger->setLoggerSubPath(__CLASS__); + if (empty($this->debugLoggerFilename)) { + $this->debugLoggerFilename = 'Log-' . date('Y-m-d') . '.log'; + } + $this->logger->setLoggerFilename($this->debugLoggerFilename); + if ($url) { + $this->setURL($url); // If $url is not Empty, call method setURL + } + $this->setMethod($method); + $this->setData($data); + $this->setHeaders($headers); + } + + /** + * GetContents destructor. + */ + public function __destruct() + { + if (self::USE_BENCHMARK === true) { + $this->benchmark->mark('code_end'); + $this->logger->debug(__FUNCTION__, 'Elapsed Time: ===> ' . $this->benchmark->elapsed_time('code_start', 'code_end')); + $this->logger->debug(__FUNCTION__, 'Memory Usage: ===> ' . $this->benchmark->memory_usage()); + } + } + + /** + * Function getContent - Get Body Content from Request + * + * @return array|mixed|object|string|null Return Response content if exists + * Full Response content if $this->response['content'] not exists + * Exception Error Message if Exception Error + * Null if Not + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/7/18 02:08 + */ + public function getContent() + { + try { + if ($this->response) { + return $this->response['content'] ?? $this->response; + } + } catch (Exception $e) { + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + + return $e->getMessage(); + } + + return null; + } + + /** + * Function getError - Get Error Code and Message + * + * @return array|mixed|object|string|null Return Response error if exists + * Full Response if $this->response['error'] not exists + * Exception Error Message if Exception Error + * Null if Not + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/9/18 09:33 + */ + public function getError() + { + try { + if ($this->response) { + return $this->response['error'] ?? $this->response; + } + } catch (Exception $e) { + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + + return $e->getMessage(); + } + + return null; + } + + /** + * Function get Response of Request + * + * @return array|mixed|object|null Array if Exists, Null if Not Response + * @author: 713uk13m + * @time : 10/7/18 01:50 + */ + public function response() + { + if ($this->response) { + return $this->response; + } + + return null; + } + + /** + * Let's go to Request + * + * @return array|null|string Response from Request if Exists + * Exception Error Message if Exception Error + * Null if Not + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:12 + */ + public function sendRequest() + { + try { + if (mb_strlen($this->url) >= 9) { + $response = $this->useFileGetContents(); + $this->response = $response; + + return $response; + } + } catch (Exception $e) { + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + + return $e->getMessage(); + } + + return null; + } + + /** + * Function useFileGetContents. Use file_get_contents to perform the request + * + * @return array The server response array + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:19 + */ + public function useFileGetContents(): array + { + $return = array(); + + // Options Setup + $options = array( + 'http' => array( + 'method' => $this->method, + 'timeout' => $this->timeout + ) + ); + + // Use SSL + if ($this->isSSL) { + $options['ssl'] = array( + 'verify_peer' => $this->verifyPeer, + 'verify_peer_name' => $this->verifyPeer + ); + } + + $headers = $this->getHeaderArray(); + + if (count($headers) > 0) { + $options['http']['header'] = implode("\r\n", $headers); + } + + if ($this->method === 'POST') { + $post = $this->getPostBody(); + if ($post !== '') { + $options['http']['content'] = $post; + } + $return['post'] = $post; + } + + $context = stream_context_create($options); + $query_string = $this->getQueryString(); + $this->logger->debug(__FUNCTION__, 'Options into Request: ', $options); + $this->logger->debug(__FUNCTION__, 'Data Query String into Request: ', $query_string); + $this->logger->debug(__FUNCTION__, 'Endpoint URL into Request: ', $this->url); + try { + $response = file_get_contents($this->url . $query_string, false, $context); + $responseHeaders = $http_response_header; + $return['headers'] = $this->parseReturnHeaders($responseHeaders); + $return['url'] = $this->url . $query_string; + if ($response) { + $return['content'] = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($response)); + if ($this->isJson === true && $this->isDecodeJson === true) { + $responseJson = json_decode(trim($return['content'])); + if (json_last_error() === JSON_ERROR_NONE) { + $return['content'] = $responseJson; + $this->logger->debug(__FUNCTION__, 'Set Response is Json: ', $return['content']); + } + } + } + } catch (Exception $e) { + $return['error'] = array( + 'code' => 500, + 'message' => 'Could not file_get_contents.', + 'extended' => $e + ); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + } + + if (isset($return['headers']['response_code'])) { + $responseType = mb_substr($return['headers']['response_code'], 0, 1); + if ($responseType !== '2') { + $return['error'] = array( + 'code' => $return['headers']['response_code'], + 'message' => 'Server returned an error.' + ); + $this->logger->error(__FUNCTION__, 'Could not file_get_contents: ', $return['error']); + } + } + + $cookies = array(); + foreach ($http_response_header as $hdr) { + if (preg_match('/^Set-Cookie:\s*([^;]+)/i', $hdr, $matches)) { + parse_str($matches[1], $tmp); + $cookies += $tmp; + } + } + + if ($this->trackCookies) { + $cookies = array_merge($this->cookies, $cookies); + $this->cookies = $cookies; + } + $return['cookies'] = $cookies; + $this->logger->info(__FUNCTION__, 'Final Result from Server: ', $return); + + return $return; + } + + /** + * Generate the complete header array. Merges the supplied (if any) headers with those needed by the request. + * + * @return array An array of headers + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:19 + */ + public function getHeaderArray(): array + { + $headerArray = (count($this->headers) > 0 ? $this->headers : []); + if ($this->isJson) { + $headerArray[] = 'Accept: application/json'; + } + if ($this->isXML) { + $headerArray[] = 'Accept: text/xml'; + } + if ($this->isJson && $this->method === 'POST' && count($this->data) > 0) { + $headerArray[] = 'Content-type: application/json'; + } elseif ($this->isXML && $this->method === 'POST' && count($this->data) > 0) { + $headerArray[] = 'Content-type: text/xml'; + } elseif ($this->method === 'POST' && count($this->data) > 0) { + $headerArray[] = 'Content-type: application/x-www-form-urlencoded'; + } + if (count($this->cookies) > 0) { + $cookies = ''; + foreach ($this->cookies as $key => $value) { + if ($cookies !== '') { + $cookies .= '; '; + } + $cookies .= urlencode($key) . '=' . urlencode($value); + } + $headerArray[] = 'Cookie: ' . $cookies; + } + + return $headerArray; + } + + /** + * Get the post body - either JSON encoded or ready to be sent as a form post + * + * @return array|false|string Data to be sent Request + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:19 + */ + public function getPostBody() + { + $output = ''; + if ($this->isJson) { + $jsonPretty = ($this->isJsonPretty ? JSON_PRETTY_PRINT : null); + if (count($this->data) > 0) { + $output = json_encode($this->data, $jsonPretty); + } + } elseif ($this->isXML) { + $output = $this->data; + } elseif (count($this->data) > 0) { + $output = http_build_query($this->data); + } + + return $output; + } + + /** + * Get the query string by merging any supplied string with that of the generated components. + * + * @return string The query string + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:19 + */ + public function getQueryString(): string + { + $query_string = ''; + if (count($this->query_string) > 0) { + $query_string .= http_build_query($this->query_string); + } + if (($this->method !== 'POST') && count($this->data) > 0) { + $query_string .= http_build_query($this->data); + } + if ($query_string !== '') { + $query_string = (mb_strpos($this->url, '?') ? '&' : '?') . $query_string; + } + + return $query_string; + } + + /** + * Set the target URL - Must include http:// or https:// + * + * @param string $url + * + * @return $this + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:10 + */ + public function setURL(string $url = ''): self + { + try { + if ($url !== '') { + if (mb_strpos($url, 'https://') === 0) { + $this->isSSL = true; + $this->logger->debug(__FUNCTION__, 'Set SSL: ' . $this->isSSL); + } elseif (mb_strpos($url, 'http://') === 0) { + $this->isSSL = true; + $this->logger->debug(__FUNCTION__, 'Set SSL: ' . $this->isSSL); + } + } + $this->url = $url; + } catch (Exception $e) { + $this->url = null; + $message = "Error: " . __CLASS__ . ": Invalid protocol specified. URL must start with http:// or https:// - " . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage(); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $message); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + } + $this->logger->debug(__FUNCTION__, 'Endpoint URL to Request: ', $this->url); + + return $this; + } + + /** + * Set the HTTP method: GET, HEAD, PUT, POST, DELETE are valid + * + * @param string $method Method to Request GET, HEAD, PUT, POST, DELETE are valid + * + * @return $this|string Method + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:15 + */ + public function setMethod(string $method = '') + { + if ($method === '') { + $this->logger->debug(__FUNCTION__, 'Set Default Method = GET if $method is does not exist'); + $method = 'GET'; + } else { + $method = mb_strtoupper($method); + $validMethods = array('GET', 'HEAD', 'PUT', 'POST', 'DELETE'); + if (!in_array($method, $validMethods)) { + $message = "Error: " . __CLASS__ . ": The requested method (" . $method . ") is not valid here"; + $this->logger->error(__FUNCTION__, $message); + + return $message; + } + } + $this->method = $method; + + return $this; + } + + /** + * Set Data contents. Must be supplied as an array + * + * @param array|string $inputData The contents to be sent to the target URL + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:18 + */ + public function setData($inputData = array()) + { + if (is_string($inputData)) { + parse_str($inputData, $data); + } else { + $data = $inputData; + } + + if (count($data) === 0) { + $this->data = array(); + } else { + $this->data = $data; + } + $this->logger->debug(__FUNCTION__, 'Data into Request: ', $this->data); + } + + /** + * Set query string data. Must be supplied as an array + * + * @param array|string $inputQueryString The query string to be sent to the target URL + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 01:36 + */ + public function setQueryString($inputQueryString = array()) + { + if (is_string($inputQueryString)) { + parse_str($inputQueryString, $queryString); + } else { + $queryString = $inputQueryString; + } + if (count($queryString) === 0) { + $this->query_string = array(); + } else { + $this->query_string = $queryString; + } + } + + /** + * Set any headers to be sent to the target URL. Must be supplied as an array + * + * @param array $headers Header to Set + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:18 + */ + public function setHeaders(array $headers = array()) + { + if (!is_array($headers)) { + $this->headers = array(); + } else { + $this->headers = $headers; + } + } + + /** + * Set any cookies to be included in the headers. Must be supplied as an array + * + * @param array $cookies The array of cookies to be sent + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:18 + */ + public function setCookies(array $cookies = array()) + { + if (!is_array($cookies)) { + $this->cookies = array(); + } else { + $this->cookies = $cookies; + $this->trackCookies = true; + } + } + + /** + * Should cookies be tracked? + * + * @param boolean $value true to track cookies + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:18 + */ + public function setTrackCookies(bool $value = false) + { + if (!$value) { + $this->trackCookies = false; + } else { + $this->trackCookies = true; + } + } + + /** + * Function setXML - Is this transaction sending / expecting XML + * + * @param bool $value true if XML is being used and is expected + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 01:38 + */ + public function setXML(bool $value = false) + { + if (!$value) { + $this->isXML = false; + } else { + $this->isXML = true; + } + } + + /** + * Is this transaction sending / expecting JSON + * + * @param boolean $value true if JSON is being used and is expected + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:17 + */ + public function setJson(bool $value = false) + { + if (!$value) { + $this->isJson = false; + } else { + $this->isJson = true; + } + } + + /** + * Should JSON being sent be encoded in an easily readable format? Only useful for debugging + * + * @param boolean $value true for JSON_PRETTY_PRINT + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:17 + */ + public function setJsonPretty(bool $value = false) + { + if (!$value) { + $this->isJsonPretty = false; + } else { + $this->isJsonPretty = true; + } + } + + /** + * Should SSL peers be verified? + * + * @param bool $value + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:17 + */ + public function setVerifyPeer(bool $value = false) + { + if (!$value) { + $this->verifyPeer = false; + } else { + $this->verifyPeer = true; + } + } + + /** + * Function setTimeout + * + * @param int $timeout + * + * @example 60 + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:17 + */ + public function setTimeout(int $timeout = 20) + { + $this->timeout = $timeout; + } + + /** + * Parse HTTP response headers + * + * @param array $headers + * + * @return array Header Response + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 02:17 + */ + public function parseReturnHeaders(array $headers): array + { + $head = array(); + foreach ($headers as $value) { + $t = explode(':', $value, 2); + if (isset($t[1])) { + $head[trim($t[0])] = trim($t[1]); + } else { + $head[] = $value; + $patternHttp = "#HTTP/[0-9\.]+\s+([0-9]+)#"; + if (preg_match($patternHttp, $value, $out)) { + $head['response_code'] = (int)$out[1]; + } + } + } + $this->logger->debug(__FUNCTION__, 'Response Header: ', $head); + + return $head; + } } diff --git a/src/Input.php b/src/Input.php index b02508d..537e7e6 100644 --- a/src/Input.php +++ b/src/Input.php @@ -24,436 +24,436 @@ */ class Input { - /** @var \Symfony\Component\HttpFoundation\Request $input */ - protected $input; - - /** @var \nguyenanhung\MyRequests\Ip $ip */ - protected $ip; - - /** - * Raw input stream data - * - * Holds a cache of php://input contents - * - * @var string - */ - protected $rawInputStream; - - /** - * Parsed input stream data - * - * Parsed from php://input at runtime - * - * @var array - */ - protected $inputStream; - - /** - * Enable XSS flag - * - * Determines whether the XSS filter is always active when - * GET, POST or COOKIE data is encountered. - * Set automatically based on config setting. - * - * @var bool - */ - protected $enableXss = false; - - /** - * List of all HTTP request headers - * - * @var array - */ - protected $headers = array(); - - /** - * Input constructor. - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function __construct() - { - $this->input = Request::createFromGlobals(); - $this->ip = new Ip(); - } - - /** - * Function rawInputStream - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 10:38 - */ - public function rawInputStream(): self - { - $rawInputStream = file_get_contents('php://input'); - $this->rawInputStream = $rawInputStream; - - return $this; - } - - /** - * Function getRawInputStream - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/04/2021 14:38 - */ - public function getRawInputStream(): string - { - return $this->rawInputStream; - } - - /** - * Function inputStream - * - * @param null $index - * @param null $xss_clean - * - * @return array|mixed|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 03/18/2021 00:18 - */ - public function inputStream($index = null, $xss_clean = null) - { - // Prior to PHP 5.6, the input stream can only be read once, - // so we'll need to check if we have already done that first. - if (!is_array($this->inputStream)) { - // $this->raw_input_stream will trigger __get(). - parse_str($this->rawInputStream, $this->inputStream); - is_array($this->inputStream) or $this->inputStream = array(); - } - - return $this->fetchFromArray($this->inputStream, $index, $xss_clean); - } - - /** - * Function method - Hàm lấy thông tin Request Method - * - * @param bool $upper Whether to return in upper or lower case (default: FALSE) - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 03/18/2021 00:27 - */ - public function method(bool $upper = false): string - { - return ($upper) - ? mb_strtoupper($this->server('REQUEST_METHOD', true)) - : mb_strtolower($this->server('REQUEST_METHOD', true)); - } - - /** - * Hàm lấy dữ liệu từ $_POST - * - * @param string|mixed $key POST parameter name - * @param bool $xss_clean Whether to apply XSS filtering - * - * @return bool|float|int|string|string[]|\Symfony\Component\HttpFoundation\InputBag|null $_POST if no parameters supplied, otherwise the POST value if found or NULL if not - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/18/18 10:58 - * - */ - public function post($key = '', bool $xss_clean = false) - { - if ($this->input->request->has($key)) { - $content = $this->input->request->get($key); - if ($xss_clean === true) { - $content = Utils::xssClean($content); - } - - return $content; - } - - return null; - } - - /** - * Hàm lấy dữ liệu từ $_GET - * - * @param string|mixed $key GET parameter name - * @param bool $xss_clean Whether to apply XSS filtering - * - * @return bool|float|int|string|string[]|\Symfony\Component\HttpFoundation\InputBag|null $_GET if no parameters supplied, otherwise the GET value if found or NULL if not - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/18/18 10:58 - * - */ - public function get($key = '', bool $xss_clean = false) - { - if ($this->input->query->has($key)) { - $content = $this->input->query->get($key); - if ($xss_clean === true) { - $content = Utils::xssClean($content); - } - - return $content; - } - - return null; - } - - /** - * Hàm lấy dữ liệu từ $_SERVER - * - * @param string|mixed $key SERVER parameter name - * @param bool $xss_clean Whether to apply XSS filtering - * - * @return bool|float|int|string|string[]|\Symfony\Component\HttpFoundation\InputBag|null $_SERVER f no parameters supplied, otherwise the SERVER value if found or NULL if not - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/18/18 10:58 - * - */ - public function server($key = '', bool $xss_clean = false) - { - if ($this->input->server->has($key)) { - $content = $this->input->server->get($key); - if ($xss_clean === true) { - $content = Utils::xssClean($content); - } - - return $content; - } - - return null; - } - - /** - * Hàm lấy dữ liệu từ $_COOKIE - * - * @param string|mixed $key COOKIE parameter name - * @param bool $xss_clean Whether to apply XSS filtering - * - * @return bool|float|int|string|string[]|\Symfony\Component\HttpFoundation\InputBag|null $_COOKIE f no parameters supplied, otherwise the COOKIE value if found or NULL if not - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/18/18 10:58 - * - */ - public function cookie($key = '', bool $xss_clean = false) - { - if ($this->input->cookies->has($key)) { - $content = $this->input->cookies->get($key); - if ($xss_clean === true) { - $content = Utils::xssClean($content); - } - - return $content; - } - - return null; - } - - /** - * Hàm lấy dữ liệu từ $_FILES - * - * @param string|mixed $key FILES parameter name - * @param bool $xss_clean Whether to apply XSS filtering - * - * @return mixed|null|string|string[] $_FILES f no parameters supplied, otherwise the FILES value if found or NULL if not - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/18/18 10:58 - * - */ - public function file($key = '', bool $xss_clean = false) - { - if ($this->input->files->has($key)) { - $content = $this->input->files->get($key); - if ($xss_clean === true) { - $content = Utils::xssClean($content); - } - - return $content; - } - - return null; - } - - /** - * Hàm lấy dữ liệu từ $_SERVER Header - * - * @param string|mixed $key _SERVER parameter name - * @param bool $xss_clean Whether to apply XSS filtering - * - * @return array|string|string[]|null $_SERVER f no parameters supplied, otherwise the _SERVER value if found or NULL if not - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/18/18 10:58 - * - */ - public function header($key = '', bool $xss_clean = false) - { - if ($this->input->headers->has($key)) { - $content = $this->input->headers->get($key); - if ($xss_clean === true) { - $content = Utils::xssClean($content); - } - - return $content; - } - - return null; - } - - /** - * Function ip_address - Hàm lấy địa chỉ IP của người dùng - * - * @return bool|int|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 13:02 - */ - public function ip_address() - { - return $this->ip->getIpAddress(); - } - - /** - * Request Headers - * - * @param bool $xss_clean Whether to apply XSS filtering - * - * @return array - */ - public function requestHeaders(bool $xss_clean = false) - { - // If header is already defined, return it immediately - if (!empty($this->headers)) { - return $this->fetchFromArray($this->headers, null, $xss_clean); - } - - // In Apache, you can simply call apache_request_headers() - if (function_exists('apache_request_headers')) { - $this->headers = apache_request_headers(); - } else { - isset($_SERVER['CONTENT_TYPE']) && $this->headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; - foreach ($_SERVER as $key => $val) { - if (sscanf($key, 'HTTP_%s', $header) === 1) { - // take SOME_HEADER and turn it into Some-Header - $header = str_replace('_', ' ', mb_strtolower($header)); - $header = str_replace(' ', '-', ucwords($header)); - $this->headers[$header] = $val; - } - } - } - - return $this->fetchFromArray($this->headers, null, $xss_clean); - } - - /** - * Get Request Header - * - * Returns the value of a single member of the headers class member - * - * @param string $index Header name - * @param bool $xss_clean Whether to apply XSS filtering - * - * @return string|null The requested header on success or NULL on failure - */ - public function getRequestHeader(string $index, bool $xss_clean = false) - { - static $headers; - if (!isset($headers)) { - empty($this->headers) && $this->requestHeaders(); - foreach ($this->headers as $key => $value) { - $headers[mb_strtolower($key)] = $value; - } - } - $index = mb_strtolower($index); - if (!isset($headers[$index])) { - return null; - } - - return ($xss_clean === true) - ? Utils::xssClean($headers[$index]) - : $headers[$index]; - } - - /** - * Is AJAX request? - * - * Test to see if a request contains the HTTP_X_REQUESTED_WITH header. - * - * @return bool - */ - public function isAjax(): bool - { - return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && mb_strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'); - } - - /** - * Is CLI request? - * - * Test to see if a request was made from the command line. - * - * @return bool - */ - public function isCLI(): bool - { - return (PHP_SAPI === 'cli' or defined('STDIN')); - } - - /** - * Fetch from Array - * - * Internal method used to retrieve values from global arrays. - * - * @param array &$array $_GET, $_POST, $_COOKIE, $_SERVER, etc. - * @param mixed $index Index for item to be fetched from $array - * @param bool|null $xss_clean Whether to apply XSS filtering - * - * @return mixed - * @copyright CodeIgniter - * - */ - public function fetchFromArray(array &$array, $index = null, bool $xss_clean = null) - { - is_bool($xss_clean) or $xss_clean = $this->enableXss; - - // If $index is NULL, it means that the whole $array is requested - isset($index) or $index = array_keys($array); - - // allow fetching multiple keys at once - if (is_array($index)) { - $output = array(); - foreach ($index as $key) { - $output[$key] = $this->fetchFromArray($array, $key, $xss_clean); - } - - return $output; - } - $patternArray = '/(?:^[^\[]+)|\[[^]]*\]/'; // Does the index contain array notation - if (isset($array[$index])) { - $value = $array[$index]; - } elseif (($count = preg_match_all($patternArray, $index, $matches)) > 1) { - $value = $array; - for ($i = 0; $i < $count; $i++) { - $key = trim($matches[0][$i], '[]'); - if ($key === '') // Empty notation will return the value as array - { - break; - } - if (isset($value[$key])) { - $value = $value[$key]; - } else { - return null; - } - } - } else { - return null; - } - - return ($xss_clean === true) - ? Utils::xssClean($value) - : $value; - } + /** @var \Symfony\Component\HttpFoundation\Request $input */ + protected $input; + + /** @var \nguyenanhung\MyRequests\Ip $ip */ + protected $ip; + + /** + * Raw input stream data + * + * Holds a cache of php://input contents + * + * @var string + */ + protected $rawInputStream; + + /** + * Parsed input stream data + * + * Parsed from php://input at runtime + * + * @var array + */ + protected $inputStream; + + /** + * Enable XSS flag + * + * Determines whether the XSS filter is always active when + * GET, POST or COOKIE data is encountered. + * Set automatically based on config setting. + * + * @var bool + */ + protected $enableXss = false; + + /** + * List of all HTTP request headers + * + * @var array + */ + protected $headers = array(); + + /** + * Input constructor. + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function __construct() + { + $this->input = Request::createFromGlobals(); + $this->ip = new Ip(); + } + + /** + * Function rawInputStream + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 10:38 + */ + public function rawInputStream(): self + { + $rawInputStream = file_get_contents('php://input'); + $this->rawInputStream = $rawInputStream; + + return $this; + } + + /** + * Function getRawInputStream + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/04/2021 14:38 + */ + public function getRawInputStream(): string + { + return $this->rawInputStream; + } + + /** + * Function inputStream + * + * @param null $index + * @param null $xss_clean + * + * @return array|mixed|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 03/18/2021 00:18 + */ + public function inputStream($index = null, $xss_clean = null) + { + // Prior to PHP 5.6, the input stream can only be read once, + // so we'll need to check if we have already done that first. + if (!is_array($this->inputStream)) { + // $this->raw_input_stream will trigger __get(). + parse_str($this->rawInputStream, $this->inputStream); + is_array($this->inputStream) or $this->inputStream = array(); + } + + return $this->fetchFromArray($this->inputStream, $index, $xss_clean); + } + + /** + * Function method - Hàm lấy thông tin Request Method + * + * @param bool $upper Whether to return in upper or lower case (default: FALSE) + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 03/18/2021 00:27 + */ + public function method(bool $upper = false): string + { + return ($upper) + ? mb_strtoupper($this->server('REQUEST_METHOD', true)) + : mb_strtolower($this->server('REQUEST_METHOD', true)); + } + + /** + * Hàm lấy dữ liệu từ $_POST + * + * @param string|mixed $key POST parameter name + * @param bool $xss_clean Whether to apply XSS filtering + * + * @return bool|float|int|string|string[]|\Symfony\Component\HttpFoundation\InputBag|null $_POST if no parameters supplied, otherwise the POST value if found or NULL if not + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/18/18 10:58 + * + */ + public function post($key = '', bool $xss_clean = false) + { + if ($this->input->request->has($key)) { + $content = $this->input->request->get($key); + if ($xss_clean === true) { + $content = Utils::xssClean($content); + } + + return $content; + } + + return null; + } + + /** + * Hàm lấy dữ liệu từ $_GET + * + * @param string|mixed $key GET parameter name + * @param bool $xss_clean Whether to apply XSS filtering + * + * @return bool|float|int|string|string[]|\Symfony\Component\HttpFoundation\InputBag|null $_GET if no parameters supplied, otherwise the GET value if found or NULL if not + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/18/18 10:58 + * + */ + public function get($key = '', bool $xss_clean = false) + { + if ($this->input->query->has($key)) { + $content = $this->input->query->get($key); + if ($xss_clean === true) { + $content = Utils::xssClean($content); + } + + return $content; + } + + return null; + } + + /** + * Hàm lấy dữ liệu từ $_SERVER + * + * @param string|mixed $key SERVER parameter name + * @param bool $xss_clean Whether to apply XSS filtering + * + * @return bool|float|int|string|string[]|\Symfony\Component\HttpFoundation\InputBag|null $_SERVER f no parameters supplied, otherwise the SERVER value if found or NULL if not + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/18/18 10:58 + * + */ + public function server($key = '', bool $xss_clean = false) + { + if ($this->input->server->has($key)) { + $content = $this->input->server->get($key); + if ($xss_clean === true) { + $content = Utils::xssClean($content); + } + + return $content; + } + + return null; + } + + /** + * Hàm lấy dữ liệu từ $_COOKIE + * + * @param string|mixed $key COOKIE parameter name + * @param bool $xss_clean Whether to apply XSS filtering + * + * @return bool|float|int|string|string[]|\Symfony\Component\HttpFoundation\InputBag|null $_COOKIE f no parameters supplied, otherwise the COOKIE value if found or NULL if not + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/18/18 10:58 + * + */ + public function cookie($key = '', bool $xss_clean = false) + { + if ($this->input->cookies->has($key)) { + $content = $this->input->cookies->get($key); + if ($xss_clean === true) { + $content = Utils::xssClean($content); + } + + return $content; + } + + return null; + } + + /** + * Hàm lấy dữ liệu từ $_FILES + * + * @param string|mixed $key FILES parameter name + * @param bool $xss_clean Whether to apply XSS filtering + * + * @return mixed|null|string|string[] $_FILES f no parameters supplied, otherwise the FILES value if found or NULL if not + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/18/18 10:58 + * + */ + public function file($key = '', bool $xss_clean = false) + { + if ($this->input->files->has($key)) { + $content = $this->input->files->get($key); + if ($xss_clean === true) { + $content = Utils::xssClean($content); + } + + return $content; + } + + return null; + } + + /** + * Hàm lấy dữ liệu từ $_SERVER Header + * + * @param string|mixed $key _SERVER parameter name + * @param bool $xss_clean Whether to apply XSS filtering + * + * @return array|string|string[]|null $_SERVER f no parameters supplied, otherwise the _SERVER value if found or NULL if not + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/18/18 10:58 + * + */ + public function header($key = '', bool $xss_clean = false) + { + if ($this->input->headers->has($key)) { + $content = $this->input->headers->get($key); + if ($xss_clean === true) { + $content = Utils::xssClean($content); + } + + return $content; + } + + return null; + } + + /** + * Function ip_address - Hàm lấy địa chỉ IP của người dùng + * + * @return bool|int|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 13:02 + */ + public function ip_address() + { + return $this->ip->getIpAddress(); + } + + /** + * Request Headers + * + * @param bool $xss_clean Whether to apply XSS filtering + * + * @return array + */ + public function requestHeaders(bool $xss_clean = false) + { + // If header is already defined, return it immediately + if (!empty($this->headers)) { + return $this->fetchFromArray($this->headers, null, $xss_clean); + } + + // In Apache, you can simply call apache_request_headers() + if (function_exists('apache_request_headers')) { + $this->headers = apache_request_headers(); + } else { + isset($_SERVER['CONTENT_TYPE']) && $this->headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; + foreach ($_SERVER as $key => $val) { + if (sscanf($key, 'HTTP_%s', $header) === 1) { + // take SOME_HEADER and turn it into Some-Header + $header = str_replace('_', ' ', mb_strtolower($header)); + $header = str_replace(' ', '-', ucwords($header)); + $this->headers[$header] = $val; + } + } + } + + return $this->fetchFromArray($this->headers, null, $xss_clean); + } + + /** + * Get Request Header + * + * Returns the value of a single member of the headers class member + * + * @param string $index Header name + * @param bool $xss_clean Whether to apply XSS filtering + * + * @return string|null The requested header on success or NULL on failure + */ + public function getRequestHeader(string $index, bool $xss_clean = false) + { + static $headers; + if (!isset($headers)) { + empty($this->headers) && $this->requestHeaders(); + foreach ($this->headers as $key => $value) { + $headers[mb_strtolower($key)] = $value; + } + } + $index = mb_strtolower($index); + if (!isset($headers[$index])) { + return null; + } + + return ($xss_clean === true) + ? Utils::xssClean($headers[$index]) + : $headers[$index]; + } + + /** + * Is AJAX request? + * + * Test to see if a request contains the HTTP_X_REQUESTED_WITH header. + * + * @return bool + */ + public function isAjax(): bool + { + return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && mb_strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'); + } + + /** + * Is CLI request? + * + * Test to see if a request was made from the command line. + * + * @return bool + */ + public function isCLI(): bool + { + return (PHP_SAPI === 'cli' or defined('STDIN')); + } + + /** + * Fetch from Array + * + * Internal method used to retrieve values from global arrays. + * + * @param array &$array $_GET, $_POST, $_COOKIE, $_SERVER, etc. + * @param mixed $index Index for item to be fetched from $array + * @param bool|null $xss_clean Whether to apply XSS filtering + * + * @return mixed + * @copyright CodeIgniter + * + */ + public function fetchFromArray(array &$array, $index = null, bool $xss_clean = null) + { + is_bool($xss_clean) or $xss_clean = $this->enableXss; + + // If $index is NULL, it means that the whole $array is requested + isset($index) or $index = array_keys($array); + + // allow fetching multiple keys at once + if (is_array($index)) { + $output = array(); + foreach ($index as $key) { + $output[$key] = $this->fetchFromArray($array, $key, $xss_clean); + } + + return $output; + } + $patternArray = '/(?:^[^\[]+)|\[[^]]*\]/'; // Does the index contain array notation + if (isset($array[$index])) { + $value = $array[$index]; + } elseif (($count = preg_match_all($patternArray, $index, $matches)) > 1) { + $value = $array; + for ($i = 0; $i < $count; $i++) { + $key = trim($matches[0][$i], '[]'); + if ($key === '') // Empty notation will return the value as array + { + break; + } + if (isset($value[$key])) { + $value = $value[$key]; + } else { + return null; + } + } + } else { + return null; + } + + return ($xss_clean === true) + ? Utils::xssClean($value) + : $value; + } } diff --git a/src/MyRequests.php b/src/MyRequests.php index e449690..43892a2 100644 --- a/src/MyRequests.php +++ b/src/MyRequests.php @@ -25,1360 +25,1360 @@ */ class MyRequests implements ProjectInterface { - use Version; - - /** - * An array of headers to be added to the request - * - * @var array - */ - private $headers = array(); - - /** - * An array of cookies (which are added to the headers) - * - * @var array - */ - private $cookies = array(); - - /** - * An array of options to be added to the request - * - * @var array - */ - private $options = array(); - - /** - * You can customize requests created and transferred by a client using request options. - * Request options control various aspects of a request including, headers, query string parameters, timeout settings, the body of a request, and much more. - * - * @var array - */ - private $requestOptions = array(); - - /** - * How long to wait for a server to respond to a request. - * - * @var integer - */ - private $timeout = 60; - - /** - * An array of userAgent to be added to the request - * - * @var array|string - */ - private $userAgent; - - /** - * A URL String referrer to be added to the request - * - * @var string - */ - private $referrer; - - /** - * An array of basicAuthentication: username, password to be added to the request - * - * @var array - */ - private $basicAuthentication; - - /** - * A string of bearerToken to be added to the request - * - * @var string - */ - private $bearerToken; - - /** - * An array of digestAuthentication: username, password to be added to the request - * - * @var array - */ - private $digestAuthentication; - - /** - * Set data request is Body - * - * @var bool - */ - private $isBody; - - /** - * Set data request is Json - * - * @var bool - */ - private $isJson; - - /** - * Set data request is XML - * - * @var bool - */ - protected $isXml; - - /** - * Set data request is SSL - * - * @var bool - */ - private $isSSL = false; - - /** - * Describes the SSL certificate verification behavior of a request. - * - * @var bool - */ - private $isVerify = true; - - /** - * Protocol version to use with the request. - * - * @var int|float - */ - private $protocolVersion = 0; - - /** - * Set Response Error is Array Data - * - * @var bool - */ - private $errorResponseIsData = false; - - /** - * Set Response Error is Null - * - * @var bool - */ - private $errorResponseIsNull = false; - - /** - * Error Code from Request - * - * @var integer - */ - private $error_code; - - /** - * Request Header array if exists, Null if not - * - * @var array|null - */ - private $requests_header; - - /** - * Response Header array if exists, Null if not - * - * @var array|null - */ - private $response_header; - - /** - * Http Code from Request - * - * @var integer - */ - private $http_code; - - /** - * Http Message from Request - * - * @var string|null - */ - private $http_message; - - /** - * @var object \nguyenanhung\MyDebug\Benchmark - */ - private $benchmark; - - /** - * @var object \nguyenanhung\MyDebug\Debug Call to class - */ - private $logger; - - /** - * Set Debug Status - * - * @var bool - */ - public $debugStatus = false; - - /** - * @var null|string Set level Debug: DEBUG, INFO, ERROR .... - */ - public $debugLevel = 'error'; - - /** - * Set Logger Path to Save - * - * @var string|null - */ - public $debugLoggerPath = ''; - - /** - * Set Logger Filename to Save - * - * @var string - */ - public $debugLoggerFilename = ''; - - /** - * MyRequests constructor. - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function __construct() - { - if (self::USE_BENCHMARK === true) { - $this->benchmark = new Benchmark(); - $this->benchmark->mark('code_start'); - } - $this->logger = new Logger(); - if (empty($this->debugLoggerPath)) { - $this->debugStatus = false; - } - $this->logger->setDebugStatus($this->debugStatus); - $this->logger->setGlobalLoggerLevel($this->debugLevel); - $this->logger->setLoggerPath($this->debugLoggerPath); - $this->logger->setLoggerSubPath(__CLASS__); - if (empty($this->debugLoggerFilename)) { - $this->debugLoggerFilename = 'Log-' . date('Y-m-d') . '.log'; - } - $this->logger->setLoggerFilename($this->debugLoggerFilename); - } - - /** - * MyRequests destructor. - */ - public function __destruct() - { - if (self::USE_BENCHMARK === true) { - $this->benchmark->mark('code_end'); - $this->logger->debug(__FUNCTION__, 'Elapsed Time: ===> ' . $this->benchmark->elapsed_time('code_start', 'code_end')); - $this->logger->debug(__FUNCTION__, 'Memory Usage: ===> ' . $this->benchmark->memory_usage()); - } - } - - /** - * Function setDebugStatus - * - * @param bool $debugStatus - * - * @return MyRequests - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function setDebugStatus(bool $debugStatus): self - { - $this->debugStatus = $debugStatus; - - return $this; - } - - /** - * Function setDebugLevel - * - * @param string|null $debugLevel - * - * @return MyRequests - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function setDebugLevel(string $debugLevel): self - { - $this->debugLevel = $debugLevel; - - return $this; - } - - /** - * Function setDebugLoggerPath - * - * @param string|null $debugLoggerPath - * - * @return MyRequests - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function setDebugLoggerPath(string $debugLoggerPath): self - { - $this->debugLoggerPath = $debugLoggerPath; - - return $this; - } - - /** - * Function setDebugLoggerFilename - * - * @param string $debugLoggerFilename - * - * @return MyRequests - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function setDebugLoggerFilename(string $debugLoggerFilename): self - { - $this->debugLoggerFilename = $debugLoggerFilename; - - return $this; - } - - /** - * Function setHeader - * - * @param array $headers - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 09:44 - */ - public function setHeader(array $headers = array()): self - { - $this->headers = $headers; - $this->logger->info(__FUNCTION__, 'setHeaders: ', $this->headers); - - return $this; - } - - /** - * Function setCookie - * - * @param array $cookies - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 09:51 - */ - public function setCookie(array $cookies = array()): self - { - $this->cookies = $cookies; - $this->logger->info(__FUNCTION__, 'setCookie: ', $this->cookies); - - return $this; - } - - /** - * Function setOptions - * - * @param array $options - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 20:13 - */ - public function setOptions(array $options = array()): self - { - $this->options = $options; - $this->logger->info(__FUNCTION__, 'setOptions: ', $this->options); - - return $this; - } - - /** - * Function setRequestOptions - * - * @param array $requestOptions - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 20:13 - */ - public function setRequestOptions(array $requestOptions = array()): self - { - $this->requestOptions = $requestOptions; - $this->logger->info(__FUNCTION__, 'setRequestOptions: ', $this->requestOptions); - return $this; - } - - /** - * Function getRequestOptions - * - * User: 713uk13m - * Copyright: 713uk13m - * @return array - */ - public function getRequestOptions(): array - { - return $this->requestOptions; - } - - /** - * Function setTimeout - * - * @param int $timeout - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 10:06 - */ - public function setTimeout(int $timeout = 60): self - { - $this->timeout = $timeout; - $this->logger->info(__FUNCTION__, 'setTimeout: ' . $this->timeout); - - return $this; - } - - /** - * Function setUserAgent - * - * @param string $userAgent - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 10:15 - */ - public function setUserAgent(string $userAgent = ''): self - { - $this->userAgent = $userAgent; - if (is_array($this->userAgent)) { - $this->logger->info(__FUNCTION__, 'setUserAgent: ', $this->userAgent); - } else { - $this->logger->info(__FUNCTION__, 'setUserAgent: ' . $this->userAgent); - } - - - return $this; - } - - /** - * Function setReferrer - * - * @param string $referrer - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 10:28 - */ - public function setReferrer(string $referrer = ''): self - { - $this->referrer = $referrer; - if (is_array($this->referrer)) { - $this->logger->info(__FUNCTION__, 'setReferrer: ', $this->referrer); - } else { - $this->logger->info(__FUNCTION__, 'setReferrer: ' . $this->referrer); - } - - return $this; - } - - /** - * Function setUserBody - * - * @param bool $isBody - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 11:34 - */ - public function setUserBody(bool $isBody = false): self - { - $this->isBody = $isBody; - if (is_array($this->isBody)) { - $this->logger->info(__FUNCTION__, 'setUserBody: ', $this->isBody); - } else { - $this->logger->info(__FUNCTION__, 'setUserBody: ' . $this->isBody); - } - - return $this; - } - - /** - * Function setRequestIsXml - * - * @param bool $isXml - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 12:00 - */ - public function setRequestIsXml(bool $isXml = false): self - { - $this->isXml = $isXml; - if ($this->isXml === true) { - $header['Accept'] = 'text/xml; charset=utf-8'; - $header['Content-type'] = 'text/xml; charset=utf-8'; - $this->headers = $header; - } - $this->logger->info(__FUNCTION__, 'setRequestIsXml: ' . $this->isXml); - - return $this; - } - - /** - * Function setRequestIsJson - * - * @param bool $isJson - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 12:31 - */ - public function setRequestIsJson(bool $isJson = false): self - { - $this->isJson = $isJson; - if ($this->isJson === true) { - $header['Accept'] = 'application/json; charset=utf-8'; - $header['Content-type'] = 'application/json; charset=utf-8'; - $this->headers = $header; - } - $this->logger->info(__FUNCTION__, 'setRequestIsJson: ' . $this->isJson); - - return $this; - } - - /** - * Function setRequestIsSSL - * - * @param bool $isSSL - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 01/21/2021 12:38 - */ - public function setRequestIsSSL(bool $isSSL = false): self - { - $this->isSSL = $isSSL; - $this->logger->info(__FUNCTION__, 'setRequestIsSSL: ' . $this->isSSL); - - return $this; - } - - /** - * Function setRequestNoVerify - * - * User: 713uk13m - * Copyright: 713uk13m - * @return $this - */ - public function setRequestNoVerify(): self - { - $this->isVerify = false; - return $this; - } - - /** - * Function setRequestProtocolVersion - * - * @param int|float $protocolVersion - * User: 713uk13m - * Copyright: 713uk13m - * @return $this - */ - public function setRequestProtocolVersion(int $protocolVersion = 0): self - { - $this->protocolVersion = $protocolVersion; - return $this; - } - - /** - * Function setErrorResponseIsData - * = true -> sẽ trả về 1 response đầy đủ error code, error message - * - * @param bool $errorResponseIsData Array Data if Response is Null if Error - * - * @return $this; - * @author: 713uk13m - * @time : 10/7/18 23:02 - * - */ - public function setErrorResponseIsData(bool $errorResponseIsData = false): self - { - $this->errorResponseIsData = $errorResponseIsData; - $this->logger->info(__FUNCTION__, 'setErrorResponseIsData: ' . $this->errorResponseIsData); - - return $this; - } - - /** - * Function setErrorResponseIsNull - * Trả về null nếu có lỗi request - * - * @param bool $errorResponseIsNull TRUE if Response is Null if Error - * - * @return $this - * @author: 713uk13m - * @time : 10/7/18 23:04 - * - */ - public function setErrorResponseIsNull(bool $errorResponseIsNull = false): self - { - $this->errorResponseIsNull = $errorResponseIsNull; - $this->logger->info(__FUNCTION__, 'setErrorResponseIsNull: ' . $this->errorResponseIsNull); - - return $this; - } - - /** - * Function setBasicAuthentication - * - * @param string $username Username to be Authentication - * @param string $password Password to be Authentication - * - * @return $this - * @author: 713uk13m - * @time : 10/7/18 05:24 - * - */ - public function setBasicAuthentication(string $username = '', string $password = ''): self - { - $this->basicAuthentication = [ - 'username' => $username, - 'password' => $password - ]; - $this->logger->info(__FUNCTION__, 'setBasicAuthentication: ', $this->basicAuthentication); - - return $this; - } - - /** - * Function setBearerToken - * - * @param string $bearerToken String BearerToken for Request - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/04/2021 18:11 - */ - public function setBearerToken(string $bearerToken = ''): self - { - $this->bearerToken = $bearerToken; - $this->logger->info(__FUNCTION__, 'setBasicAuthentication: ', $this->basicAuthentication); - - return $this; - } - - /** - * Function setDigestAuthentication - * - * @param string $username Username to be Authentication - * @param string $password Password to be Authentication - * - * @return $this - * @author: 713uk13m - * @time : 10/7/18 06:28 - * - */ - public function setDigestAuthentication(string $username = '', string $password = ''): self - { - $this->digestAuthentication = [$username, $password, 'digest']; - $this->logger->info(__FUNCTION__, 'setDigestAuthentication: ', $this->digestAuthentication); - - return $this; - } - - /** - * Function getHttpCode - * - * @return int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/01/2021 12:11 - */ - public function getHttpCode(): int - { - return $this->http_code; - } - - /** - * Function getHttpMessage - * - * @return string|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/01/2021 12:09 - */ - public function getHttpMessage() - { - return $this->http_message; - } - - /** - * Function getErrorCode - * - * @return int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/01/2021 12:06 - */ - public function getErrorCode(): int - { - return $this->error_code; - } - - /** - * Function getRequestsHeader - * - * @return array|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/01/2021 12:04 - */ - public function getRequestsHeader() - { - return $this->requests_header; - } - - /** - * Function getResponseHeader - * - * @return array|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/01/2021 12:01 - */ - public function getResponseHeader() - { - return $this->response_header; - } - - /** - * Function guzzlePhpRequest - * Send Request use GuzzleHttp\Client - https://packagist.org/packages/guzzlehttp/guzzle - * - * @param string $url URL Endpoint to be Request - * @param array $data Data Content to be Request - * @param string $method Set Method to be Request - * - * @return array|\Psr\Http\Message\ResponseInterface|\Psr\Http\Message\StreamInterface|string|null - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 06:45 - * - * @see https://packagist.org/packages/guzzlehttp/guzzle - */ - public function guzzlePhpRequest(string $url = '', array $data = array(), string $method = 'GET') - { - $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); - $inputParams = array('url' => $url, 'data' => $data, 'method' => $method); - $this->logger->debug(__FUNCTION__, 'input Params: ', $inputParams); - $method = mb_strtoupper($method); - $endpoint = trim($url); - $this->logger->debug(__FUNCTION__, 'cURL Endpoint: ' . $endpoint); - if (PHP_VERSION_ID < 50400) { - return $this->curlRequest($url, $data, $method); - } - if (!class_exists(Client::class)) { - $this->logger->critical(__FUNCTION__, 'class GuzzleHttp\Client is not exits'); - $result = null; - } else { - try { - $client = new Client(); - // Create options - $options = array( - 'timeout' => $this->timeout, - 'connect_timeout' => $this->timeout - ); - if (is_array($this->headers) && count($this->headers) > 0) { - $options['headers'] = $this->headers; - } - if (is_array($this->cookies) && count($this->cookies) > 0) { - $options['cookies'] = $this->cookies; - } - if ($this->basicAuthentication) { - $options['auth'] = $this->basicAuthentication; - } - if ($this->digestAuthentication) { - $options['auth'] = $this->digestAuthentication; - } - if ($this->bearerToken) { - $options['headers'] = [ - 'Authorization' => 'Bearer ' . $this->bearerToken - ]; - } - if (($this->isBody === true) && ($method === self::POST || $method === self::PUT || $method === self::PATCH || $method === self::OPTIONS)) { - if ($this->isJson) { - $options['body'] = json_encode($data); - } else { - $options['body'] = $data; - } - } else { - $options['query'] = $data; - } - if (!empty($this->options)) { - $clientOptions = array_merge($options, $this->options, $this->requestOptions); - } else { - $clientOptions = array_merge($options, $this->requestOptions); - } - $this->setOptions($clientOptions); - if ($method === self::GET) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::GET . ' request to ' . $url . ' with Data: ', $data); - $request = $client->get($endpoint, $this->options); - } elseif ($method === self::HEAD) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::HEAD . ' request to ' . $url . ' with Data: ', $data); - $request = $client->head($endpoint, $this->options); - } elseif ($method === self::DELETE) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::DELETE . ' request to ' . $url . ' with Data: ', $data); - $request = $client->delete($endpoint, $this->options); - } elseif ($method === self::POST) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::POST . ' request to ' . $url . ' with Data: ', $data); - $request = $client->post($endpoint, $this->options); - } elseif ($method === self::PUT) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::PUT . ' request to ' . $url . ' with Data: ', $data); - $request = $client->put($endpoint, $this->options); - } elseif ($method === self::PATCH) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::PATCH . ' request to ' . $url . ' with Data: ', $data); - $request = $client->patch($endpoint, $this->options); - } else { - $this->logger->debug(__FUNCTION__, 'Make DEFAULT request to ' . $url . ' with Data: ', $data); - $request = $client->get($endpoint, $this->options); - } - // Debug - $status_code = $request->getStatusCode(); - $status_message = $request->getReasonPhrase(); - $http_error = in_array(floor($this->http_code / 100), [4, 5], true); - $error_code = array( - 'status' => $status_code, - 'error' => $status_code, - 'error_code' => $status_code, - 'error_message' => $status_message, - 'http_error' => array( - 'http_error' => $http_error, - 'http_status_code' => $status_code, - 'http_error_message' => $status_message - ), - 'headers' => array( - 'request_headers' => $this->headers, - 'response_headers' => $request->getHeaders() - ), - 'data' => array( - 'status' => $request->getStatusCode(), - 'error_code' => $request->getStatusCode(), - 'error_message' => $request->getReasonPhrase(), - 'reasonPhrase' => $request->getReasonPhrase(), - 'protocolVersion' => $request->getProtocolVersion(), - 'headers' => $request->getHeaders(), - 'requests_url' => $endpoint, - 'requests_options' => $this->options, - 'response_body' => $request->getBody() - ) - ); - $this->http_code = $status_code; - $this->http_message = $request->getReasonPhrase(); - $this->error_code = $error_code; - $this->logger->debug(__FUNCTION__, 'Full Data Curl Message and Http Message: ', $error_code); - if ($http_error) { - if ($this->errorResponseIsData === true) { - $this->logger->debug(__FUNCTION__, 'Return Error Response is Array Data'); - $result = $error_code; - } elseif ($this->errorResponseIsNull === true) { - $this->logger->debug(__FUNCTION__, 'Return Error Response is Null'); - $result = null; - } else { - $result = $request; - $this->logger->debug(__FUNCTION__, 'Return Error Response is Message: ' . json_encode($result)); - } - } else { - $result = $request->getBody(); - } - } catch (GuzzleException $exception) { - $result = "Error File: " . $exception->getFile() . ' - Line: ' . $exception->getLine() . ' Code: ' . $exception->getCode() . ' - Message: ' . $exception->getMessage(); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $exception->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $exception->getTraceAsString()); - } catch (Exception $e) { - $result = "Error File: " . $e->getFile() . ' - Line: ' . $e->getLine() . ' Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage(); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - } - } - if (is_array($result) || is_object($result)) { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($result)); - } else { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($result)); - } - - return $result; - } - - /** - * Function curlRequest - * Send Request use \Curl\Curl class - https://packagist.org/packages/curl/curl - * - * @param string $url URL Endpoint to be Request - * @param array|string $data Data Content to be Request - * @param string $method Set Method to be Request - * - * @return array|null|string Response content from server, - * null of Exception Message if Error - * @author: 713uk13m - * @time : 10/7/18 05:54 - * - * @see https://packagist.org/packages/php-curl-class/php-curl-class - */ - public function curlRequest(string $url = '', array $data = array(), string $method = 'GET') - { - $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); - $inputParams = array('url' => $url, 'data' => $data, 'method' => $method); - $this->logger->info(__FUNCTION__, 'input Params: ', $inputParams); - $method = mb_strtoupper($method); - if (!class_exists(Curl::class)) { - $this->logger->critical(__FUNCTION__, 'class \Curl\Curl() is not exits'); - $response = null; - } else { - try { - $curl = new Curl(); - if ($this->isJson) { - $data = json_encode($data); - $this->logger->debug(__FUNCTION__, 'isJson Data: ' . $data); - } - if ($this->userAgent) { - $curl->setUserAgent($this->userAgent); - } - if (is_array($this->headers) && count($this->headers) > 0) { - foreach ($this->headers as $key => $value) { - $curl->setHeader($key, $value); - } - } - if (is_array($this->cookies) && count($this->cookies) > 0) { - foreach ($this->cookies as $key => $value) { - $curl->setCookie($key, $value); - } - } - if ($this->basicAuthentication) { - $curl->setBasicAuthentication($this->basicAuthentication['username'], $this->basicAuthentication['password']); - } - if ($this->bearerToken) { - $curl->setHeader("Authorization", 'Bearer ' . $this->bearerToken); - } - if ($this->referrer) { - $curl->setReferer($this->referrer); - } - $parseUrl = parse_url($url); - $curl->setOpt(CURLOPT_RETURNTRANSFER, self::RETURN_TRANSFER); - $curl->setOpt(CURLOPT_SSL_VERIFYPEER, $this->isSSL); - $curl->setOpt(CURLOPT_SSL_VERIFYHOST, $this->isSSL); - if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'https') { - $curl->setOpt(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); - } - if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'http') { - $curl->setOpt(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); - } - $curl->setOpt(CURLOPT_SSLVERSION, 6); - $curl->setOpt(CURLOPT_ENCODING, self::ENCODING); - $curl->setOpt(CURLOPT_MAXREDIRS, self::MAX_REDIRECT); - $curl->setOpt(CURLOPT_TIMEOUT, $this->timeout); - $curl->setOpt(CURLOPT_CONNECTTIMEOUT, $this->timeout); - $curl->setOpt(CURLOPT_FOLLOWLOCATION, self::FOLLOW_LOCATION); - // Request - if (self::POST === $method) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::POST . ' request to ' . $url . ' with Data: ', $data); - $curl->post($url, $data); - } elseif (self::PUT === $method) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::PUT . ' request to ' . $url . ' with Data: ', $data); - $curl->put($url, $data); - } elseif (self::PATCH === $method) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::PATCH . ' request to ' . $url . ' with Data: ', $data); - $curl->patch($url, $data); - } elseif (self::DELETE === $method) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::DELETE . ' request to ' . $url . ' with Data: ', $data); - $curl->delete($url, $data); - } elseif (self::OPTIONS === $method) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::OPTIONS . ' request to ' . $url . ' with Data: ', $data); - $curl->options($url, $data); - } elseif (self::HEAD === $method) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::HEAD . ' request to ' . $url . ' with Data: ', $data); - $curl->head($url, $data); - } elseif (self::GET === $method) { - $this->logger->debug(__FUNCTION__, 'Make ' . self::GET . ' request to ' . $url . ' with Data: ', $data); - $curl->get($url, $data); - } else { - $this->logger->debug(__FUNCTION__, 'Make DEFAULT request to ' . $url . ' with Data: ', $data); - $curl->get($url, $data); - } - $error_code = $this->curlRequestErrorParse($curl); - // Set Vars - $this->error_code = $error_code; - $this->http_code = $error_code['http_error']['http_status_code']; - $this->http_message = $error_code['http_error']['http_error_message']; - $this->requests_header = $error_code['headers']['request_headers']; - $this->response_header = $error_code['headers']['response_headers']; - // Response - if ($curl->error) { - // Debug - $this->logger->debug(__FUNCTION__, 'Full Data Curl Message and Http Message: ', $error_code); - if ($this->errorResponseIsData === true) { - $this->logger->debug(__FUNCTION__, 'Return Error Response is Array Data'); - $response = $error_code; - } elseif ($this->errorResponseIsNull === true) { - $this->logger->debug(__FUNCTION__, 'Return Error Response is Null'); - $response = null; - } else { - $errMsg = $error_code['error_message']; - $response = "cURL Error: " . $errMsg; - $this->logger->debug(__FUNCTION__, 'Return Error Response is Message: ' . $response); - } - } else { - if ($curl->rawResponse) { - $response = $curl->rawResponse; - } elseif (isset($curl->response)) { - $response = $curl->response; - } else { - $response = null; - } - $this->logger->debug(__FUNCTION__, 'Response from Request, no Error: ' . $response); - } - // Close Request - $curl->close(); - // Log Response - if (isset($response)) { - if (is_array($response) || is_object($response)) { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($response)); - } else { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($response)); - } - } - } catch (Exception $e) { - $response = "Error File: " . $e->getFile() . ' - Line: ' . $e->getLine() . ' Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage(); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - } - } - - return $response; - } - - /** - * Function curlRequestErrorParse - * - * @param object $curl - * - * @return array - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/24/2021 17:53 - */ - protected function curlRequestErrorParse($curl): array - { - if ($curl->errorCode) { - $resErrorCode = $curl->errorCode; - } elseif (isset($curl->error_code)) { - $resErrorCode = $curl->error_code; - } else { - $resErrorCode = null; - } - if ($curl->errorMessage) { - $resErrorMessage = $curl->errorMessage; - } elseif (isset($curl->error_message)) { - $resErrorMessage = $curl->error_message; - } else { - $resErrorMessage = null; - } - if ($curl->curlError) { - $resErrorCurl = $curl->curlError; - } elseif (isset($curl->curl_error)) { - $resErrorCurl = $curl->curl_error; - } else { - $resErrorCurl = null; - } - if ($curl->curlErrorCode) { - $resErrorCurlCode = $curl->curlErrorCode; - } elseif (isset($curl->curl_error_code)) { - $resErrorCurlCode = $curl->curl_error_code; - } else { - $resErrorCurlCode = null; - } - if ($curl->curlErrorMessage) { - $resErrorCurlMessage = $curl->curlErrorMessage; - } elseif (isset($curl->curl_error_message)) { - $resErrorCurlMessage = $curl->curl_error_message; - } else { - $resErrorCurlMessage = null; - } - if ($curl->httpError) { - $resErrorHttp = $curl->httpError; - } elseif (isset($curl->http_error)) { - $resErrorHttp = $curl->http_error; - } else { - $resErrorHttp = null; - } - if ($curl->httpStatusCode) { - $resErrorHttpStatusCode = $curl->httpStatusCode; - } elseif (isset($curl->curl_status_code)) { - $resErrorHttpStatusCode = $curl->curl_status_code; - } else { - $resErrorHttpStatusCode = null; - } - if ($curl->httpErrorMessage) { - $resErrorHttpMessage = $curl->httpErrorMessage; - } elseif (isset($curl->curl_error_message)) { - $resErrorHttpMessage = $curl->curl_error_message; - } else { - $resErrorHttpMessage = null; - } - if ($curl->requestHeaders) { - $resRequestHeaders = $curl->requestHeaders; - } elseif (isset($curl->request_headers)) { - $resRequestHeaders = $curl->request_headers; - } else { - $resRequestHeaders = null; - } - if ($curl->responseHeaders) { - $resResponseHeaders = $curl->responseHeaders; - } elseif (isset($curl->response_headers)) { - $resResponseHeaders = $curl->response_headers; - } else { - $resResponseHeaders = null; - } - - return array( - 'status' => $resErrorCode, - 'error' => $curl->error, - 'error_code' => $resErrorCode, - 'error_message' => $resErrorMessage, - 'curl_error' => array( - 'curl_error' => $resErrorCurl, - 'curl_error_code' => $resErrorCurlCode, - 'curl_error_message' => $resErrorCurlMessage - ), - 'http_error' => array( - 'http_error' => $resErrorHttp, - 'http_status_code' => $resErrorHttpStatusCode, - 'http_error_message' => $resErrorHttpMessage - ), - 'headers' => array( - 'request_headers' => $resRequestHeaders, - 'response_headers' => $resResponseHeaders - ) - ); - } - - /** - * Function sendRequest - * Handle send Request use Multi Method - * - * @param string $url URL Endpoint to be Request - * @param array|string $data Data Content to be Request - * @param string $method Set Method to be Request - * - * @return array|mixed|object|\Psr\Http\Message\ResponseInterface|\Psr\Http\Message\StreamInterface|string|null Response content from server - * null of Exception Message if Error - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 07:07 - */ - public function sendRequest(string $url = '', $data = array(), string $method = 'GET') - { - $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); - $inputParams = array('url' => $url, 'data' => $data, 'method' => $method); - $this->logger->debug(__FUNCTION__, 'input Params: ', $inputParams); - $method = mb_strtoupper($method); - $endpoint = trim($url); - $this->logger->debug(__FUNCTION__, 'cURL Endpoint: ' . $endpoint); - if (!extension_loaded('curl')) { - $this->logger->critical(__FUNCTION__, 'Server is not Support cURL, Please cURL. Library fallback user File Get Contents'); - // Create Request use File Get Content - $content = new GetContents(); - $content->debugStatus = $this->debugStatus; - $content->debugLoggerPath = $this->debugLoggerPath; - $content->__construct(); - $content->setURL($url); - $content->setMethod($method); - $content->setHeaders($this->headers); - $content->setData($data); - $content->sendRequest(); - // Create Request - $result = $content->response(); - $getContent = $content->getContent(); - $getError = $content->getError(); - $this->logger->debug(__FUNCTION__, 'Get Content Result: ' . $getContent); - $this->logger->debug(__FUNCTION__, 'Get Error Result: ' . $getError); - } else { - try { - $useGuzzlePhp = [self::HEAD, self::TRACE, self::OPTIONS]; - $this->logger->debug(__FUNCTION__, 'Make ' . $method . ' request to ' . $url . ' with Data: ', $data); - if (in_array($method, $useGuzzlePhp, true)) { - $result = $this->guzzlePhpRequest($url, $data, $method); - } else { - $result = $this->curlRequest($url, $data, $method); - } - } catch (Exception $e) { - $result = "Error File: " . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage(); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - } - } - if (is_array($result) || is_object($result)) { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($result)); - } else { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($result)); - } - if (is_array($result) || is_object($result)) { - $result = json_encode($result); - } - - return $result; - } - - /** - * Function xmlRequest - * Send XML Request to Server - * - * @param string $url URL Endpoint to be Request - * @param string $data Data Content to be Request - * @param int $timeout Timeout Request - * - * @return array|null|string Response from Server - * @author: 713uk13m - * @time : 10/7/18 07:11 - * - */ - public function xmlRequest(string $url = '', string $data = '', int $timeout = 60) - { - $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); - $endpoint = trim($url); - $this->logger->debug(__FUNCTION__, 'cURL Endpoint: ' . $endpoint); - $inputParams = array('url' => $url, 'data' => $data, 'timeout' => $timeout); - $this->logger->debug(__FUNCTION__, 'input Params: ', $inputParams); - if (!extension_loaded('curl')) { - $this->logger->critical(__FUNCTION__, 'Server is not Support cURL, Please cURL. Library fallback user File Get Contents'); - // Create Request use File Get Content - $content = new GetContents(); - $content->debugStatus = $this->debugStatus; - $content->debugLoggerPath = $this->debugLoggerPath; - $content->__construct(); - $content->setURL($url); - $content->setMethod('POST'); - $content->setXML(true); - $content->setData($data); - $content->sendRequest(); - // Create Request - $result = $content->response(); - $getContent = $content->getContent(); - $getError = $content->getError(); - $this->logger->debug(__FUNCTION__, 'Get Content Result: ' . $getContent); - $this->logger->debug(__FUNCTION__, 'Get Error Result: ' . $getError); - } else { - $this->setRequestIsXml(true); - $this->setTimeout($timeout); - $result = $this->curlRequest($url, $data, 'POST'); - } - if (is_array($result) || is_object($result)) { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($result)); - } else { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($result)); - } - - return $result; - } - - /** - * Function jsonRequest - * Send JSON Request to Server - * - * @param string $url URL Endpoint to be Request - * @param array $data Data Content to be Request - * @param int $timeout Timeout Request - * - * @return array|null|string Response from Server - * @author: 713uk13m - * @time : 10/7/18 07:13 - * - */ - public function jsonRequest(string $url = '', array $data = array(), int $timeout = 60) - { - $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); - $endpoint = trim($url); - $this->logger->debug(__FUNCTION__, 'cURL Endpoint: ' . $endpoint); - $inputParams = array('url' => $url, 'data' => $data, 'timeout' => $timeout); - $this->logger->debug(__FUNCTION__, 'input Params: ', $inputParams); - if (!extension_loaded('curl')) { - $this->logger->critical(__FUNCTION__, 'Server is not Support cURL, Please cURL. Library fallback user File Get Contents'); - // Create Request use File Get Content - $content = new GetContents(); - $content->debugStatus = $this->debugStatus; - $content->debugLoggerPath = $this->debugLoggerPath; - $content->__construct(); - $content->setURL($url); - $content->setMethod('POST'); - $content->setJson(true); - $content->setData($data); - $content->sendRequest(); - // Create Request - $result = $content->response(); - $getContent = $content->getContent(); - $getError = $content->getError(); - $this->logger->debug(__FUNCTION__, 'Get Content Result: ' . $getContent); - $this->logger->debug(__FUNCTION__, 'Get Error Result: ' . $getError); - } else { - $this->setRequestIsJson(true); - $this->setTimeout($timeout); - $result = $this->curlRequest($url, $data, 'POST'); - } - if (is_array($result) || is_object($result)) { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($result)); - } else { - $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($result)); - } - if (is_object($result) || is_array($result)) { - $result = json_encode($result); - } - - return $result; - } - - /** - * Function xmlGetValue - * - * @param string $xml XML String - * @param string $openTag OpenTag to find - * @param string $closeTag CloseTag to find - * - * @return string Result from Tag, Empty string if not - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 06:57 - */ - public function xmlGetValue(string $xml = '', string $openTag = '', string $closeTag = ''): string - { - if (empty($xml) || empty($openTag) || empty($closeTag)) { - return ''; - } - $f = mb_strpos($xml, $openTag) + mb_strlen($openTag); - $l = mb_strpos($xml, $closeTag); - - return ($f <= $l) ? mb_substr($xml, $f, $l - $f) : ""; - } - - /** - * Function parseXmlDataRequest - * - * @param string $resultXml XML String to Parse - * - * @return string|false - * - * @author : 713uk13m - * @copyright : 713uk13m - * @time : 10/7/18 06:57 - */ - public function parseXmlDataRequest(string $resultXml = '') - { - $array = array( - 'ec' => $this->xmlGetValue($resultXml, "", ""), - 'msg' => $this->xmlGetValue($resultXml, "", "") - ); - - return json_encode($array); - } + use Version; + + /** + * An array of headers to be added to the request + * + * @var array + */ + private $headers = array(); + + /** + * An array of cookies (which are added to the headers) + * + * @var array + */ + private $cookies = array(); + + /** + * An array of options to be added to the request + * + * @var array + */ + private $options = array(); + + /** + * You can customize requests created and transferred by a client using request options. + * Request options control various aspects of a request including, headers, query string parameters, timeout settings, the body of a request, and much more. + * + * @var array + */ + private $requestOptions = array(); + + /** + * How long to wait for a server to respond to a request. + * + * @var integer + */ + private $timeout = 60; + + /** + * An array of userAgent to be added to the request + * + * @var array|string + */ + private $userAgent; + + /** + * A URL String referrer to be added to the request + * + * @var string + */ + private $referrer; + + /** + * An array of basicAuthentication: username, password to be added to the request + * + * @var array + */ + private $basicAuthentication; + + /** + * A string of bearerToken to be added to the request + * + * @var string + */ + private $bearerToken; + + /** + * An array of digestAuthentication: username, password to be added to the request + * + * @var array + */ + private $digestAuthentication; + + /** + * Set data request is Body + * + * @var bool + */ + private $isBody; + + /** + * Set data request is Json + * + * @var bool + */ + private $isJson; + + /** + * Set data request is XML + * + * @var bool + */ + protected $isXml; + + /** + * Set data request is SSL + * + * @var bool + */ + private $isSSL = false; + + /** + * Describes the SSL certificate verification behavior of a request. + * + * @var bool + */ + private $isVerify = true; + + /** + * Protocol version to use with the request. + * + * @var int|float + */ + private $protocolVersion = 0; + + /** + * Set Response Error is Array Data + * + * @var bool + */ + private $errorResponseIsData = false; + + /** + * Set Response Error is Null + * + * @var bool + */ + private $errorResponseIsNull = false; + + /** + * Error Code from Request + * + * @var integer + */ + private $error_code; + + /** + * Request Header array if exists, Null if not + * + * @var array|null + */ + private $requests_header; + + /** + * Response Header array if exists, Null if not + * + * @var array|null + */ + private $response_header; + + /** + * Http Code from Request + * + * @var integer + */ + private $http_code; + + /** + * Http Message from Request + * + * @var string|null + */ + private $http_message; + + /** + * @var object \nguyenanhung\MyDebug\Benchmark + */ + private $benchmark; + + /** + * @var object \nguyenanhung\MyDebug\Debug Call to class + */ + private $logger; + + /** + * Set Debug Status + * + * @var bool + */ + public $debugStatus = false; + + /** + * @var null|string Set level Debug: DEBUG, INFO, ERROR .... + */ + public $debugLevel = 'error'; + + /** + * Set Logger Path to Save + * + * @var string|null + */ + public $debugLoggerPath = ''; + + /** + * Set Logger Filename to Save + * + * @var string + */ + public $debugLoggerFilename = ''; + + /** + * MyRequests constructor. + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function __construct() + { + if (self::USE_BENCHMARK === true) { + $this->benchmark = new Benchmark(); + $this->benchmark->mark('code_start'); + } + $this->logger = new Logger(); + if (empty($this->debugLoggerPath)) { + $this->debugStatus = false; + } + $this->logger->setDebugStatus($this->debugStatus); + $this->logger->setGlobalLoggerLevel($this->debugLevel); + $this->logger->setLoggerPath($this->debugLoggerPath); + $this->logger->setLoggerSubPath(__CLASS__); + if (empty($this->debugLoggerFilename)) { + $this->debugLoggerFilename = 'Log-' . date('Y-m-d') . '.log'; + } + $this->logger->setLoggerFilename($this->debugLoggerFilename); + } + + /** + * MyRequests destructor. + */ + public function __destruct() + { + if (self::USE_BENCHMARK === true) { + $this->benchmark->mark('code_end'); + $this->logger->debug(__FUNCTION__, 'Elapsed Time: ===> ' . $this->benchmark->elapsed_time('code_start', 'code_end')); + $this->logger->debug(__FUNCTION__, 'Memory Usage: ===> ' . $this->benchmark->memory_usage()); + } + } + + /** + * Function setDebugStatus + * + * @param bool $debugStatus + * + * @return MyRequests + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function setDebugStatus(bool $debugStatus): self + { + $this->debugStatus = $debugStatus; + + return $this; + } + + /** + * Function setDebugLevel + * + * @param string|null $debugLevel + * + * @return MyRequests + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function setDebugLevel(string $debugLevel): self + { + $this->debugLevel = $debugLevel; + + return $this; + } + + /** + * Function setDebugLoggerPath + * + * @param string|null $debugLoggerPath + * + * @return MyRequests + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function setDebugLoggerPath(string $debugLoggerPath): self + { + $this->debugLoggerPath = $debugLoggerPath; + + return $this; + } + + /** + * Function setDebugLoggerFilename + * + * @param string $debugLoggerFilename + * + * @return MyRequests + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function setDebugLoggerFilename(string $debugLoggerFilename): self + { + $this->debugLoggerFilename = $debugLoggerFilename; + + return $this; + } + + /** + * Function setHeader + * + * @param array $headers + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 09:44 + */ + public function setHeader(array $headers = array()): self + { + $this->headers = $headers; + $this->logger->info(__FUNCTION__, 'setHeaders: ', $this->headers); + + return $this; + } + + /** + * Function setCookie + * + * @param array $cookies + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 09:51 + */ + public function setCookie(array $cookies = array()): self + { + $this->cookies = $cookies; + $this->logger->info(__FUNCTION__, 'setCookie: ', $this->cookies); + + return $this; + } + + /** + * Function setOptions + * + * @param array $options + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 20:13 + */ + public function setOptions(array $options = array()): self + { + $this->options = $options; + $this->logger->info(__FUNCTION__, 'setOptions: ', $this->options); + + return $this; + } + + /** + * Function setRequestOptions + * + * @param array $requestOptions + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 20:13 + */ + public function setRequestOptions(array $requestOptions = array()): self + { + $this->requestOptions = $requestOptions; + $this->logger->info(__FUNCTION__, 'setRequestOptions: ', $this->requestOptions); + return $this; + } + + /** + * Function getRequestOptions + * + * User: 713uk13m + * Copyright: 713uk13m + * @return array + */ + public function getRequestOptions(): array + { + return $this->requestOptions; + } + + /** + * Function setTimeout + * + * @param int $timeout + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 10:06 + */ + public function setTimeout(int $timeout = 60): self + { + $this->timeout = $timeout; + $this->logger->info(__FUNCTION__, 'setTimeout: ' . $this->timeout); + + return $this; + } + + /** + * Function setUserAgent + * + * @param string $userAgent + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 10:15 + */ + public function setUserAgent(string $userAgent = ''): self + { + $this->userAgent = $userAgent; + if (is_array($this->userAgent)) { + $this->logger->info(__FUNCTION__, 'setUserAgent: ', $this->userAgent); + } else { + $this->logger->info(__FUNCTION__, 'setUserAgent: ' . $this->userAgent); + } + + + return $this; + } + + /** + * Function setReferrer + * + * @param string $referrer + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 10:28 + */ + public function setReferrer(string $referrer = ''): self + { + $this->referrer = $referrer; + if (is_array($this->referrer)) { + $this->logger->info(__FUNCTION__, 'setReferrer: ', $this->referrer); + } else { + $this->logger->info(__FUNCTION__, 'setReferrer: ' . $this->referrer); + } + + return $this; + } + + /** + * Function setUserBody + * + * @param bool $isBody + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 11:34 + */ + public function setUserBody(bool $isBody = false): self + { + $this->isBody = $isBody; + if (is_array($this->isBody)) { + $this->logger->info(__FUNCTION__, 'setUserBody: ', $this->isBody); + } else { + $this->logger->info(__FUNCTION__, 'setUserBody: ' . $this->isBody); + } + + return $this; + } + + /** + * Function setRequestIsXml + * + * @param bool $isXml + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 12:00 + */ + public function setRequestIsXml(bool $isXml = false): self + { + $this->isXml = $isXml; + if ($this->isXml === true) { + $header['Accept'] = 'text/xml; charset=utf-8'; + $header['Content-type'] = 'text/xml; charset=utf-8'; + $this->headers = $header; + } + $this->logger->info(__FUNCTION__, 'setRequestIsXml: ' . $this->isXml); + + return $this; + } + + /** + * Function setRequestIsJson + * + * @param bool $isJson + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 12:31 + */ + public function setRequestIsJson(bool $isJson = false): self + { + $this->isJson = $isJson; + if ($this->isJson === true) { + $header['Accept'] = 'application/json; charset=utf-8'; + $header['Content-type'] = 'application/json; charset=utf-8'; + $this->headers = $header; + } + $this->logger->info(__FUNCTION__, 'setRequestIsJson: ' . $this->isJson); + + return $this; + } + + /** + * Function setRequestIsSSL + * + * @param bool $isSSL + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 01/21/2021 12:38 + */ + public function setRequestIsSSL(bool $isSSL = false): self + { + $this->isSSL = $isSSL; + $this->logger->info(__FUNCTION__, 'setRequestIsSSL: ' . $this->isSSL); + + return $this; + } + + /** + * Function setRequestNoVerify + * + * User: 713uk13m + * Copyright: 713uk13m + * @return $this + */ + public function setRequestNoVerify(): self + { + $this->isVerify = false; + return $this; + } + + /** + * Function setRequestProtocolVersion + * + * @param int|float $protocolVersion + * User: 713uk13m + * Copyright: 713uk13m + * @return $this + */ + public function setRequestProtocolVersion(int $protocolVersion = 0): self + { + $this->protocolVersion = $protocolVersion; + return $this; + } + + /** + * Function setErrorResponseIsData + * = true -> sẽ trả về 1 response đầy đủ error code, error message + * + * @param bool $errorResponseIsData Array Data if Response is Null if Error + * + * @return $this; + * @author: 713uk13m + * @time : 10/7/18 23:02 + * + */ + public function setErrorResponseIsData(bool $errorResponseIsData = false): self + { + $this->errorResponseIsData = $errorResponseIsData; + $this->logger->info(__FUNCTION__, 'setErrorResponseIsData: ' . $this->errorResponseIsData); + + return $this; + } + + /** + * Function setErrorResponseIsNull + * Trả về null nếu có lỗi request + * + * @param bool $errorResponseIsNull TRUE if Response is Null if Error + * + * @return $this + * @author: 713uk13m + * @time : 10/7/18 23:04 + * + */ + public function setErrorResponseIsNull(bool $errorResponseIsNull = false): self + { + $this->errorResponseIsNull = $errorResponseIsNull; + $this->logger->info(__FUNCTION__, 'setErrorResponseIsNull: ' . $this->errorResponseIsNull); + + return $this; + } + + /** + * Function setBasicAuthentication + * + * @param string $username Username to be Authentication + * @param string $password Password to be Authentication + * + * @return $this + * @author: 713uk13m + * @time : 10/7/18 05:24 + * + */ + public function setBasicAuthentication(string $username = '', string $password = ''): self + { + $this->basicAuthentication = [ + 'username' => $username, + 'password' => $password + ]; + $this->logger->info(__FUNCTION__, 'setBasicAuthentication: ', $this->basicAuthentication); + + return $this; + } + + /** + * Function setBearerToken + * + * @param string $bearerToken String BearerToken for Request + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/04/2021 18:11 + */ + public function setBearerToken(string $bearerToken = ''): self + { + $this->bearerToken = $bearerToken; + $this->logger->info(__FUNCTION__, 'setBasicAuthentication: ', $this->basicAuthentication); + + return $this; + } + + /** + * Function setDigestAuthentication + * + * @param string $username Username to be Authentication + * @param string $password Password to be Authentication + * + * @return $this + * @author: 713uk13m + * @time : 10/7/18 06:28 + * + */ + public function setDigestAuthentication(string $username = '', string $password = ''): self + { + $this->digestAuthentication = [$username, $password, 'digest']; + $this->logger->info(__FUNCTION__, 'setDigestAuthentication: ', $this->digestAuthentication); + + return $this; + } + + /** + * Function getHttpCode + * + * @return int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/01/2021 12:11 + */ + public function getHttpCode(): int + { + return $this->http_code; + } + + /** + * Function getHttpMessage + * + * @return string|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/01/2021 12:09 + */ + public function getHttpMessage() + { + return $this->http_message; + } + + /** + * Function getErrorCode + * + * @return int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/01/2021 12:06 + */ + public function getErrorCode(): int + { + return $this->error_code; + } + + /** + * Function getRequestsHeader + * + * @return array|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/01/2021 12:04 + */ + public function getRequestsHeader() + { + return $this->requests_header; + } + + /** + * Function getResponseHeader + * + * @return array|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/01/2021 12:01 + */ + public function getResponseHeader() + { + return $this->response_header; + } + + /** + * Function guzzlePhpRequest + * Send Request use GuzzleHttp\Client - https://packagist.org/packages/guzzlehttp/guzzle + * + * @param string $url URL Endpoint to be Request + * @param array $data Data Content to be Request + * @param string $method Set Method to be Request + * + * @return array|\Psr\Http\Message\ResponseInterface|\Psr\Http\Message\StreamInterface|string|null + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 06:45 + * + * @see https://packagist.org/packages/guzzlehttp/guzzle + */ + public function guzzlePhpRequest(string $url = '', array $data = array(), string $method = 'GET') + { + $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); + $inputParams = array('url' => $url, 'data' => $data, 'method' => $method); + $this->logger->debug(__FUNCTION__, 'input Params: ', $inputParams); + $method = mb_strtoupper($method); + $endpoint = trim($url); + $this->logger->debug(__FUNCTION__, 'cURL Endpoint: ' . $endpoint); + if (PHP_VERSION_ID < 50400) { + return $this->curlRequest($url, $data, $method); + } + if (!class_exists(Client::class)) { + $this->logger->critical(__FUNCTION__, 'class GuzzleHttp\Client is not exits'); + $result = null; + } else { + try { + $client = new Client(); + // Create options + $options = array( + 'timeout' => $this->timeout, + 'connect_timeout' => $this->timeout + ); + if (is_array($this->headers) && count($this->headers) > 0) { + $options['headers'] = $this->headers; + } + if (is_array($this->cookies) && count($this->cookies) > 0) { + $options['cookies'] = $this->cookies; + } + if ($this->basicAuthentication) { + $options['auth'] = $this->basicAuthentication; + } + if ($this->digestAuthentication) { + $options['auth'] = $this->digestAuthentication; + } + if ($this->bearerToken) { + $options['headers'] = [ + 'Authorization' => 'Bearer ' . $this->bearerToken + ]; + } + if (($this->isBody === true) && ($method === self::POST || $method === self::PUT || $method === self::PATCH || $method === self::OPTIONS)) { + if ($this->isJson) { + $options['body'] = json_encode($data); + } else { + $options['body'] = $data; + } + } else { + $options['query'] = $data; + } + if (!empty($this->options)) { + $clientOptions = array_merge($options, $this->options, $this->requestOptions); + } else { + $clientOptions = array_merge($options, $this->requestOptions); + } + $this->setOptions($clientOptions); + if ($method === self::GET) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::GET . ' request to ' . $url . ' with Data: ', $data); + $request = $client->get($endpoint, $this->options); + } elseif ($method === self::HEAD) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::HEAD . ' request to ' . $url . ' with Data: ', $data); + $request = $client->head($endpoint, $this->options); + } elseif ($method === self::DELETE) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::DELETE . ' request to ' . $url . ' with Data: ', $data); + $request = $client->delete($endpoint, $this->options); + } elseif ($method === self::POST) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::POST . ' request to ' . $url . ' with Data: ', $data); + $request = $client->post($endpoint, $this->options); + } elseif ($method === self::PUT) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::PUT . ' request to ' . $url . ' with Data: ', $data); + $request = $client->put($endpoint, $this->options); + } elseif ($method === self::PATCH) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::PATCH . ' request to ' . $url . ' with Data: ', $data); + $request = $client->patch($endpoint, $this->options); + } else { + $this->logger->debug(__FUNCTION__, 'Make DEFAULT request to ' . $url . ' with Data: ', $data); + $request = $client->get($endpoint, $this->options); + } + // Debug + $status_code = $request->getStatusCode(); + $status_message = $request->getReasonPhrase(); + $http_error = in_array(floor($this->http_code / 100), [4, 5], true); + $error_code = array( + 'status' => $status_code, + 'error' => $status_code, + 'error_code' => $status_code, + 'error_message' => $status_message, + 'http_error' => array( + 'http_error' => $http_error, + 'http_status_code' => $status_code, + 'http_error_message' => $status_message + ), + 'headers' => array( + 'request_headers' => $this->headers, + 'response_headers' => $request->getHeaders() + ), + 'data' => array( + 'status' => $request->getStatusCode(), + 'error_code' => $request->getStatusCode(), + 'error_message' => $request->getReasonPhrase(), + 'reasonPhrase' => $request->getReasonPhrase(), + 'protocolVersion' => $request->getProtocolVersion(), + 'headers' => $request->getHeaders(), + 'requests_url' => $endpoint, + 'requests_options' => $this->options, + 'response_body' => $request->getBody() + ) + ); + $this->http_code = $status_code; + $this->http_message = $request->getReasonPhrase(); + $this->error_code = $error_code; + $this->logger->debug(__FUNCTION__, 'Full Data Curl Message and Http Message: ', $error_code); + if ($http_error) { + if ($this->errorResponseIsData === true) { + $this->logger->debug(__FUNCTION__, 'Return Error Response is Array Data'); + $result = $error_code; + } elseif ($this->errorResponseIsNull === true) { + $this->logger->debug(__FUNCTION__, 'Return Error Response is Null'); + $result = null; + } else { + $result = $request; + $this->logger->debug(__FUNCTION__, 'Return Error Response is Message: ' . json_encode($result)); + } + } else { + $result = $request->getBody(); + } + } catch (GuzzleException $exception) { + $result = "Error File: " . $exception->getFile() . ' - Line: ' . $exception->getLine() . ' Code: ' . $exception->getCode() . ' - Message: ' . $exception->getMessage(); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $exception->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $exception->getTraceAsString()); + } catch (Exception $e) { + $result = "Error File: " . $e->getFile() . ' - Line: ' . $e->getLine() . ' Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage(); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + } + } + if (is_array($result) || is_object($result)) { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($result)); + } else { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($result)); + } + + return $result; + } + + /** + * Function curlRequest + * Send Request use \Curl\Curl class - https://packagist.org/packages/curl/curl + * + * @param string $url URL Endpoint to be Request + * @param array|string $data Data Content to be Request + * @param string $method Set Method to be Request + * + * @return array|null|string Response content from server, + * null of Exception Message if Error + * @author: 713uk13m + * @time : 10/7/18 05:54 + * + * @see https://packagist.org/packages/php-curl-class/php-curl-class + */ + public function curlRequest(string $url = '', array $data = array(), string $method = 'GET') + { + $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); + $inputParams = array('url' => $url, 'data' => $data, 'method' => $method); + $this->logger->info(__FUNCTION__, 'input Params: ', $inputParams); + $method = mb_strtoupper($method); + if (!class_exists(Curl::class)) { + $this->logger->critical(__FUNCTION__, 'class \Curl\Curl() is not exits'); + $response = null; + } else { + try { + $curl = new Curl(); + if ($this->isJson) { + $data = json_encode($data); + $this->logger->debug(__FUNCTION__, 'isJson Data: ' . $data); + } + if ($this->userAgent) { + $curl->setUserAgent($this->userAgent); + } + if (is_array($this->headers) && count($this->headers) > 0) { + foreach ($this->headers as $key => $value) { + $curl->setHeader($key, $value); + } + } + if (is_array($this->cookies) && count($this->cookies) > 0) { + foreach ($this->cookies as $key => $value) { + $curl->setCookie($key, $value); + } + } + if ($this->basicAuthentication) { + $curl->setBasicAuthentication($this->basicAuthentication['username'], $this->basicAuthentication['password']); + } + if ($this->bearerToken) { + $curl->setHeader("Authorization", 'Bearer ' . $this->bearerToken); + } + if ($this->referrer) { + $curl->setReferer($this->referrer); + } + $parseUrl = parse_url($url); + $curl->setOpt(CURLOPT_RETURNTRANSFER, self::RETURN_TRANSFER); + $curl->setOpt(CURLOPT_SSL_VERIFYPEER, $this->isSSL); + $curl->setOpt(CURLOPT_SSL_VERIFYHOST, $this->isSSL); + if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'https') { + $curl->setOpt(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); + } + if (isset($parseUrl['scheme']) && $parseUrl['scheme'] === 'http') { + $curl->setOpt(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); + } + $curl->setOpt(CURLOPT_SSLVERSION, 6); + $curl->setOpt(CURLOPT_ENCODING, self::ENCODING); + $curl->setOpt(CURLOPT_MAXREDIRS, self::MAX_REDIRECT); + $curl->setOpt(CURLOPT_TIMEOUT, $this->timeout); + $curl->setOpt(CURLOPT_CONNECTTIMEOUT, $this->timeout); + $curl->setOpt(CURLOPT_FOLLOWLOCATION, self::FOLLOW_LOCATION); + // Request + if (self::POST === $method) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::POST . ' request to ' . $url . ' with Data: ', $data); + $curl->post($url, $data); + } elseif (self::PUT === $method) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::PUT . ' request to ' . $url . ' with Data: ', $data); + $curl->put($url, $data); + } elseif (self::PATCH === $method) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::PATCH . ' request to ' . $url . ' with Data: ', $data); + $curl->patch($url, $data); + } elseif (self::DELETE === $method) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::DELETE . ' request to ' . $url . ' with Data: ', $data); + $curl->delete($url, $data); + } elseif (self::OPTIONS === $method) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::OPTIONS . ' request to ' . $url . ' with Data: ', $data); + $curl->options($url, $data); + } elseif (self::HEAD === $method) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::HEAD . ' request to ' . $url . ' with Data: ', $data); + $curl->head($url, $data); + } elseif (self::GET === $method) { + $this->logger->debug(__FUNCTION__, 'Make ' . self::GET . ' request to ' . $url . ' with Data: ', $data); + $curl->get($url, $data); + } else { + $this->logger->debug(__FUNCTION__, 'Make DEFAULT request to ' . $url . ' with Data: ', $data); + $curl->get($url, $data); + } + $error_code = $this->curlRequestErrorParse($curl); + // Set Vars + $this->error_code = $error_code; + $this->http_code = $error_code['http_error']['http_status_code']; + $this->http_message = $error_code['http_error']['http_error_message']; + $this->requests_header = $error_code['headers']['request_headers']; + $this->response_header = $error_code['headers']['response_headers']; + // Response + if ($curl->error) { + // Debug + $this->logger->debug(__FUNCTION__, 'Full Data Curl Message and Http Message: ', $error_code); + if ($this->errorResponseIsData === true) { + $this->logger->debug(__FUNCTION__, 'Return Error Response is Array Data'); + $response = $error_code; + } elseif ($this->errorResponseIsNull === true) { + $this->logger->debug(__FUNCTION__, 'Return Error Response is Null'); + $response = null; + } else { + $errMsg = $error_code['error_message']; + $response = "cURL Error: " . $errMsg; + $this->logger->debug(__FUNCTION__, 'Return Error Response is Message: ' . $response); + } + } else { + if ($curl->rawResponse) { + $response = $curl->rawResponse; + } elseif (isset($curl->response)) { + $response = $curl->response; + } else { + $response = null; + } + $this->logger->debug(__FUNCTION__, 'Response from Request, no Error: ' . $response); + } + // Close Request + $curl->close(); + // Log Response + if (isset($response)) { + if (is_array($response) || is_object($response)) { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($response)); + } else { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($response)); + } + } + } catch (Exception $e) { + $response = "Error File: " . $e->getFile() . ' - Line: ' . $e->getLine() . ' Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage(); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + } + } + + return $response; + } + + /** + * Function curlRequestErrorParse + * + * @param object $curl + * + * @return array + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/24/2021 17:53 + */ + protected function curlRequestErrorParse($curl): array + { + if ($curl->errorCode) { + $resErrorCode = $curl->errorCode; + } elseif (isset($curl->error_code)) { + $resErrorCode = $curl->error_code; + } else { + $resErrorCode = null; + } + if ($curl->errorMessage) { + $resErrorMessage = $curl->errorMessage; + } elseif (isset($curl->error_message)) { + $resErrorMessage = $curl->error_message; + } else { + $resErrorMessage = null; + } + if ($curl->curlError) { + $resErrorCurl = $curl->curlError; + } elseif (isset($curl->curl_error)) { + $resErrorCurl = $curl->curl_error; + } else { + $resErrorCurl = null; + } + if ($curl->curlErrorCode) { + $resErrorCurlCode = $curl->curlErrorCode; + } elseif (isset($curl->curl_error_code)) { + $resErrorCurlCode = $curl->curl_error_code; + } else { + $resErrorCurlCode = null; + } + if ($curl->curlErrorMessage) { + $resErrorCurlMessage = $curl->curlErrorMessage; + } elseif (isset($curl->curl_error_message)) { + $resErrorCurlMessage = $curl->curl_error_message; + } else { + $resErrorCurlMessage = null; + } + if ($curl->httpError) { + $resErrorHttp = $curl->httpError; + } elseif (isset($curl->http_error)) { + $resErrorHttp = $curl->http_error; + } else { + $resErrorHttp = null; + } + if ($curl->httpStatusCode) { + $resErrorHttpStatusCode = $curl->httpStatusCode; + } elseif (isset($curl->curl_status_code)) { + $resErrorHttpStatusCode = $curl->curl_status_code; + } else { + $resErrorHttpStatusCode = null; + } + if ($curl->httpErrorMessage) { + $resErrorHttpMessage = $curl->httpErrorMessage; + } elseif (isset($curl->curl_error_message)) { + $resErrorHttpMessage = $curl->curl_error_message; + } else { + $resErrorHttpMessage = null; + } + if ($curl->requestHeaders) { + $resRequestHeaders = $curl->requestHeaders; + } elseif (isset($curl->request_headers)) { + $resRequestHeaders = $curl->request_headers; + } else { + $resRequestHeaders = null; + } + if ($curl->responseHeaders) { + $resResponseHeaders = $curl->responseHeaders; + } elseif (isset($curl->response_headers)) { + $resResponseHeaders = $curl->response_headers; + } else { + $resResponseHeaders = null; + } + + return array( + 'status' => $resErrorCode, + 'error' => $curl->error, + 'error_code' => $resErrorCode, + 'error_message' => $resErrorMessage, + 'curl_error' => array( + 'curl_error' => $resErrorCurl, + 'curl_error_code' => $resErrorCurlCode, + 'curl_error_message' => $resErrorCurlMessage + ), + 'http_error' => array( + 'http_error' => $resErrorHttp, + 'http_status_code' => $resErrorHttpStatusCode, + 'http_error_message' => $resErrorHttpMessage + ), + 'headers' => array( + 'request_headers' => $resRequestHeaders, + 'response_headers' => $resResponseHeaders + ) + ); + } + + /** + * Function sendRequest + * Handle send Request use Multi Method + * + * @param string $url URL Endpoint to be Request + * @param array|string $data Data Content to be Request + * @param string $method Set Method to be Request + * + * @return array|mixed|object|\Psr\Http\Message\ResponseInterface|\Psr\Http\Message\StreamInterface|string|null Response content from server + * null of Exception Message if Error + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 07:07 + */ + public function sendRequest(string $url = '', $data = array(), string $method = 'GET') + { + $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); + $inputParams = array('url' => $url, 'data' => $data, 'method' => $method); + $this->logger->debug(__FUNCTION__, 'input Params: ', $inputParams); + $method = mb_strtoupper($method); + $endpoint = trim($url); + $this->logger->debug(__FUNCTION__, 'cURL Endpoint: ' . $endpoint); + if (!extension_loaded('curl')) { + $this->logger->critical(__FUNCTION__, 'Server is not Support cURL, Please cURL. Library fallback user File Get Contents'); + // Create Request use File Get Content + $content = new GetContents(); + $content->debugStatus = $this->debugStatus; + $content->debugLoggerPath = $this->debugLoggerPath; + $content->__construct(); + $content->setURL($url); + $content->setMethod($method); + $content->setHeaders($this->headers); + $content->setData($data); + $content->sendRequest(); + // Create Request + $result = $content->response(); + $getContent = $content->getContent(); + $getError = $content->getError(); + $this->logger->debug(__FUNCTION__, 'Get Content Result: ' . $getContent); + $this->logger->debug(__FUNCTION__, 'Get Error Result: ' . $getError); + } else { + try { + $useGuzzlePhp = [self::HEAD, self::TRACE, self::OPTIONS]; + $this->logger->debug(__FUNCTION__, 'Make ' . $method . ' request to ' . $url . ' with Data: ', $data); + if (in_array($method, $useGuzzlePhp, true)) { + $result = $this->guzzlePhpRequest($url, $data, $method); + } else { + $result = $this->curlRequest($url, $data, $method); + } + } catch (Exception $e) { + $result = "Error File: " . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage(); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + } + } + if (is_array($result) || is_object($result)) { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($result)); + } else { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($result)); + } + if (is_array($result) || is_object($result)) { + $result = json_encode($result); + } + + return $result; + } + + /** + * Function xmlRequest + * Send XML Request to Server + * + * @param string $url URL Endpoint to be Request + * @param string $data Data Content to be Request + * @param int $timeout Timeout Request + * + * @return array|null|string Response from Server + * @author: 713uk13m + * @time : 10/7/18 07:11 + * + */ + public function xmlRequest(string $url = '', string $data = '', int $timeout = 60) + { + $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); + $endpoint = trim($url); + $this->logger->debug(__FUNCTION__, 'cURL Endpoint: ' . $endpoint); + $inputParams = array('url' => $url, 'data' => $data, 'timeout' => $timeout); + $this->logger->debug(__FUNCTION__, 'input Params: ', $inputParams); + if (!extension_loaded('curl')) { + $this->logger->critical(__FUNCTION__, 'Server is not Support cURL, Please cURL. Library fallback user File Get Contents'); + // Create Request use File Get Content + $content = new GetContents(); + $content->debugStatus = $this->debugStatus; + $content->debugLoggerPath = $this->debugLoggerPath; + $content->__construct(); + $content->setURL($url); + $content->setMethod('POST'); + $content->setXML(true); + $content->setData($data); + $content->sendRequest(); + // Create Request + $result = $content->response(); + $getContent = $content->getContent(); + $getError = $content->getError(); + $this->logger->debug(__FUNCTION__, 'Get Content Result: ' . $getContent); + $this->logger->debug(__FUNCTION__, 'Get Error Result: ' . $getError); + } else { + $this->setRequestIsXml(true); + $this->setTimeout($timeout); + $result = $this->curlRequest($url, $data, 'POST'); + } + if (is_array($result) || is_object($result)) { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($result)); + } else { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($result)); + } + + return $result; + } + + /** + * Function jsonRequest + * Send JSON Request to Server + * + * @param string $url URL Endpoint to be Request + * @param array $data Data Content to be Request + * @param int $timeout Timeout Request + * + * @return array|null|string Response from Server + * @author: 713uk13m + * @time : 10/7/18 07:13 + * + */ + public function jsonRequest(string $url = '', array $data = array(), int $timeout = 60) + { + $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); + $endpoint = trim($url); + $this->logger->debug(__FUNCTION__, 'cURL Endpoint: ' . $endpoint); + $inputParams = array('url' => $url, 'data' => $data, 'timeout' => $timeout); + $this->logger->debug(__FUNCTION__, 'input Params: ', $inputParams); + if (!extension_loaded('curl')) { + $this->logger->critical(__FUNCTION__, 'Server is not Support cURL, Please cURL. Library fallback user File Get Contents'); + // Create Request use File Get Content + $content = new GetContents(); + $content->debugStatus = $this->debugStatus; + $content->debugLoggerPath = $this->debugLoggerPath; + $content->__construct(); + $content->setURL($url); + $content->setMethod('POST'); + $content->setJson(true); + $content->setData($data); + $content->sendRequest(); + // Create Request + $result = $content->response(); + $getContent = $content->getContent(); + $getError = $content->getError(); + $this->logger->debug(__FUNCTION__, 'Get Content Result: ' . $getContent); + $this->logger->debug(__FUNCTION__, 'Get Error Result: ' . $getError); + } else { + $this->setRequestIsJson(true); + $this->setTimeout($timeout); + $result = $this->curlRequest($url, $data, 'POST'); + } + if (is_array($result) || is_object($result)) { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . json_encode($result)); + } else { + $this->logger->debug(__FUNCTION__, 'Final Result from Request: ' . trim($result)); + } + if (is_object($result) || is_array($result)) { + $result = json_encode($result); + } + + return $result; + } + + /** + * Function xmlGetValue + * + * @param string $xml XML String + * @param string $openTag OpenTag to find + * @param string $closeTag CloseTag to find + * + * @return string Result from Tag, Empty string if not + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 06:57 + */ + public function xmlGetValue(string $xml = '', string $openTag = '', string $closeTag = ''): string + { + if (empty($xml) || empty($openTag) || empty($closeTag)) { + return ''; + } + $f = mb_strpos($xml, $openTag) + mb_strlen($openTag); + $l = mb_strpos($xml, $closeTag); + + return ($f <= $l) ? mb_substr($xml, $f, $l - $f) : ""; + } + + /** + * Function parseXmlDataRequest + * + * @param string $resultXml XML String to Parse + * + * @return string|false + * + * @author : 713uk13m + * @copyright : 713uk13m + * @time : 10/7/18 06:57 + */ + public function parseXmlDataRequest(string $resultXml = '') + { + $array = array( + 'ec' => $this->xmlGetValue($resultXml, "", ""), + 'msg' => $this->xmlGetValue($resultXml, "", "") + ); + + return json_encode($array); + } } diff --git a/src/ProjectInterface.php b/src/ProjectInterface.php index 085fae5..d2baa9b 100644 --- a/src/ProjectInterface.php +++ b/src/ProjectInterface.php @@ -18,30 +18,30 @@ */ interface ProjectInterface { - const VERSION = '3.1.1'; - const LAST_MODIFIED = '2023-10-14'; - const MIN_PHP_VERSION = '7.0'; - const GET = 'GET'; - const HEAD = 'HEAD'; - const DELETE = 'DELETE'; - const TRACE = 'TRACE'; - const POST = 'POST'; - const PUT = 'PUT'; - const OPTIONS = 'OPTIONS'; - const PATCH = 'PATCH'; - const ENCODING = "utf-8"; - const MAX_REDIRECT = 10; - const RETURN_TRANSFER = true; - const FOLLOW_LOCATION = true; - const USE_BENCHMARK = false; + const VERSION = '3.1.2'; + const LAST_MODIFIED = '2024-04-02'; + const MIN_PHP_VERSION = '7.0'; + const GET = 'GET'; + const HEAD = 'HEAD'; + const DELETE = 'DELETE'; + const TRACE = 'TRACE'; + const POST = 'POST'; + const PUT = 'PUT'; + const OPTIONS = 'OPTIONS'; + const PATCH = 'PATCH'; + const ENCODING = "utf-8"; + const MAX_REDIRECT = 10; + const RETURN_TRANSFER = true; + const FOLLOW_LOCATION = true; + const USE_BENCHMARK = false; - /** - * Hàm lấy phiên bản hiện tại của Package - * - * @return string Phiên bản hiện tại của Package, VD: 3.0.2 - * @author: 713uk13m - * @time : 10/7/18 01:05 - * - */ - public function getVersion(): string; + /** + * Hàm lấy phiên bản hiện tại của Package + * + * @return string Phiên bản hiện tại của Package, VD: 3.0.2 + * @author: 713uk13m + * @time : 10/7/18 01:05 + * + */ + public function getVersion(): string; } diff --git a/src/SoapRequest.php b/src/SoapRequest.php index 6734e81..3401db0 100644 --- a/src/SoapRequest.php +++ b/src/SoapRequest.php @@ -23,327 +23,327 @@ */ class SoapRequest implements ProjectInterface { - use Version; + use Version; - const SOAP_ENCODING = 'utf-8'; // Default SOAP Encoding + const SOAP_ENCODING = 'utf-8'; // Default SOAP Encoding - const XML_ENCODING = 'utf-8'; // Default XML Encoding + const XML_ENCODING = 'utf-8'; // Default XML Encoding - const DECODE_UTF8 = false; // Default Decode UTF8 Status + const DECODE_UTF8 = false; // Default Decode UTF8 Status - const FIELD_FOUND_OR_FULL = 0; - const FIELD_NOT_FOUND = 1; - const EXCEPTION_FOUND = 2; + const FIELD_FOUND_OR_FULL = 0; + const FIELD_NOT_FOUND = 1; + const EXCEPTION_FOUND = 2; - /**@var string Url Endpoint to Request */ - private $endpoint; - /**@var array Data to Request */ - private $data; - /**@var string Function to Request SOAP Service */ - private $callFunction; - /**@var string Field Result to mapping Response request */ - private $fieldResult; - /**@var bool Set Json Encode Response to Output */ - private $responseIsJson; - /**@var object \nguyenanhung\MyDebug\Benchmark */ - private $benchmark; - /**@var object \nguyenanhung\MyDebug\Debug Call to class */ - private $logger; - /** @var bool Debug Status */ - public $debugStatus = false; - /** @var null|string Set level Debug: DEBUG, INFO, ERROR .... */ - public $debugLevel = 'error'; - /** @var string Set Logger Path to Save */ - public $debugLoggerPath = ''; - /** @var string|null Set Logger Filename to Save */ - public $debugLoggerFilename = ''; + /**@var string Url Endpoint to Request */ + private $endpoint; + /**@var array Data to Request */ + private $data; + /**@var string Function to Request SOAP Service */ + private $callFunction; + /**@var string Field Result to mapping Response request */ + private $fieldResult; + /**@var bool Set Json Encode Response to Output */ + private $responseIsJson; + /**@var object \nguyenanhung\MyDebug\Benchmark */ + private $benchmark; + /**@var object \nguyenanhung\MyDebug\Debug Call to class */ + private $logger; + /** @var bool Debug Status */ + public $debugStatus = false; + /** @var null|string Set level Debug: DEBUG, INFO, ERROR .... */ + public $debugLevel = 'error'; + /** @var string Set Logger Path to Save */ + public $debugLoggerPath = ''; + /** @var string|null Set Logger Filename to Save */ + public $debugLoggerFilename = ''; - /** - * SoapRequest constructor. - * - * @author : 713uk13m - * @copyright: 713uk13m - */ - public function __construct() - { - if (self::USE_BENCHMARK === true) { - $this->benchmark = new Benchmark(); - $this->benchmark->mark('code_start'); - } - $this->logger = new Logger(); - if (empty($this->debugLoggerPath)) { - $this->debugStatus = false; - } - $this->logger->setDebugStatus($this->debugStatus); - $this->logger->setGlobalLoggerLevel($this->debugLevel); - $this->logger->setLoggerPath($this->debugLoggerPath); - $this->logger->setLoggerSubPath(__CLASS__); - if (empty($this->debugLoggerFilename)) { - $this->debugLoggerFilename = 'Log-' . date('Y-m-d') . '.log'; - } - $this->logger->setLoggerFilename($this->debugLoggerFilename); - } + /** + * SoapRequest constructor. + * + * @author : 713uk13m + * @copyright: 713uk13m + */ + public function __construct() + { + if (self::USE_BENCHMARK === true) { + $this->benchmark = new Benchmark(); + $this->benchmark->mark('code_start'); + } + $this->logger = new Logger(); + if (empty($this->debugLoggerPath)) { + $this->debugStatus = false; + } + $this->logger->setDebugStatus($this->debugStatus); + $this->logger->setGlobalLoggerLevel($this->debugLevel); + $this->logger->setLoggerPath($this->debugLoggerPath); + $this->logger->setLoggerSubPath(__CLASS__); + if (empty($this->debugLoggerFilename)) { + $this->debugLoggerFilename = 'Log-' . date('Y-m-d') . '.log'; + } + $this->logger->setLoggerFilename($this->debugLoggerFilename); + } - /** - * SoapRequest destructor. - */ - public function __destruct() - { - if (self::USE_BENCHMARK === true) { - $this->benchmark->mark('code_end'); - $this->logger->debug(__FUNCTION__, 'Elapsed Time: ===> ' . $this->benchmark->elapsed_time('code_start', 'code_end')); - $this->logger->debug(__FUNCTION__, 'Memory Usage: ===> ' . $this->benchmark->memory_usage()); - } - } + /** + * SoapRequest destructor. + */ + public function __destruct() + { + if (self::USE_BENCHMARK === true) { + $this->benchmark->mark('code_end'); + $this->logger->debug(__FUNCTION__, 'Elapsed Time: ===> ' . $this->benchmark->elapsed_time('code_start', 'code_end')); + $this->logger->debug(__FUNCTION__, 'Memory Usage: ===> ' . $this->benchmark->memory_usage()); + } + } - /** - * Function setEndpoint - Cấu hình URL SOAP Endpoint cần gọi - * - * @param string $endpoint Link to Url Endpoint - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 32:50 - */ - public function setEndpoint(string $endpoint = ''): self - { - $this->endpoint = $endpoint; - $this->logger->debug(__FUNCTION__, 'setEndpoint: ' . $this->endpoint); + /** + * Function setEndpoint - Cấu hình URL SOAP Endpoint cần gọi + * + * @param string $endpoint Link to Url Endpoint + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 32:50 + */ + public function setEndpoint(string $endpoint = ''): self + { + $this->endpoint = $endpoint; + $this->logger->debug(__FUNCTION__, 'setEndpoint: ' . $this->endpoint); - return $this; - } + return $this; + } - /** - * Function setData - Cấu hình dữ liệu cần gọi qua SOAP Request - * - * @param array $data Data to SOAP Request, call - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 33:22 - */ - public function setData(array $data = array()): self - { - $this->data = $data; - $this->logger->debug(__FUNCTION__, 'setData: ', $this->data); + /** + * Function setData - Cấu hình dữ liệu cần gọi qua SOAP Request + * + * @param array $data Data to SOAP Request, call + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 33:22 + */ + public function setData(array $data = array()): self + { + $this->data = $data; + $this->logger->debug(__FUNCTION__, 'setData: ', $this->data); - return $this; - } + return $this; + } - /** - * Function setCallFunction - Cấu hình hàm SOAP cần gọi trong Endpoint - * - * @param string $callFunction Require Set Function to call SOAP endpoint - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 34:00 - */ - public function setCallFunction(string $callFunction = ''): self - { - $this->callFunction = $callFunction; - $this->logger->debug(__FUNCTION__, 'setCallFunction: ' . $this->callFunction); + /** + * Function setCallFunction - Cấu hình hàm SOAP cần gọi trong Endpoint + * + * @param string $callFunction Require Set Function to call SOAP endpoint + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 34:00 + */ + public function setCallFunction(string $callFunction = ''): self + { + $this->callFunction = $callFunction; + $this->logger->debug(__FUNCTION__, 'setCallFunction: ' . $this->callFunction); - return $this; - } + return $this; + } - /** - * Function setFieldResult - Nếu input giá trì vào đây, result sẽ map trực tiếp đến mã này, nếu không có sẽ trả error luôn - * - * @param string $fieldResult If input fieldResult, result return $response[$fieldResult] f - * from Response SOAP Service - * Return Error Code if not find $fieldResult from Response - * - * @return $this - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 34:39 - * - */ - public function setFieldResult(string $fieldResult = ''): self - { - $this->fieldResult = $fieldResult; - $this->logger->debug(__FUNCTION__, 'setFieldResult: ' . $this->fieldResult); + /** + * Function setFieldResult - Nếu input giá trì vào đây, result sẽ map trực tiếp đến mã này, nếu không có sẽ trả error luôn + * + * @param string $fieldResult If input fieldResult, result return $response[$fieldResult] f + * from Response SOAP Service + * Return Error Code if not find $fieldResult from Response + * + * @return $this + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 34:39 + * + */ + public function setFieldResult(string $fieldResult = ''): self + { + $this->fieldResult = $fieldResult; + $this->logger->debug(__FUNCTION__, 'setFieldResult: ' . $this->fieldResult); - return $this; - } + return $this; + } - /** - * Function setResponseIsJson - Return Response is Json if value = true - * - * @param bool $responseIsJson - * - * @return $this if set value = TRUE, response is Json string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/8/18 19:00 - * - * @see clientRequestWsdl() method - */ - public function setResponseIsJson(bool $responseIsJson = false): self - { - $this->responseIsJson = $responseIsJson; - $this->logger->debug(__FUNCTION__, 'setResponseIsJson: ' . $this->responseIsJson); + /** + * Function setResponseIsJson - Return Response is Json if value = true + * + * @param bool $responseIsJson + * + * @return $this if set value = TRUE, response is Json string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/8/18 19:00 + * + * @see clientRequestWsdl() method + */ + public function setResponseIsJson(bool $responseIsJson = false): self + { + $this->responseIsJson = $responseIsJson; + $this->logger->debug(__FUNCTION__, 'setResponseIsJson: ' . $this->responseIsJson); - return $this; - } + return $this; + } - /** - * Function clientRequestWsdl - Hàm khởi tạo reques tới endpoint qua giao thức WSDL - * - * @return array|false|string|null Call to SOAP request and received Response from Server - * Return is Json String if set setResponseIsJson(true) - * Return Null if class nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not - * exists - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 10/7/18 02:41 - */ - public function clientRequestWsdl() - { - $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); - if (!class_exists(nusoap_client::class)) { - $this->logger->critical(__FUNCTION__, 'nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not exists'); + /** + * Function clientRequestWsdl - Hàm khởi tạo reques tới endpoint qua giao thức WSDL + * + * @return array|false|string|null Call to SOAP request and received Response from Server + * Return is Json String if set setResponseIsJson(true) + * Return Null if class nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not + * exists + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 10/7/18 02:41 + */ + public function clientRequestWsdl() + { + $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); + if (!class_exists(nusoap_client::class)) { + $this->logger->critical(__FUNCTION__, 'nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not exists'); - return null; - } - try { - $client = new nusoap_client($this->endpoint, true); - $client->soap_defencoding = self::SOAP_ENCODING; - $client->xml_encoding = self::XML_ENCODING; - $client->decode_utf8 = self::DECODE_UTF8; - $error = $client->getError(); - if ($error) { - $message = "Client Request WSDL Error: " . json_encode($error); - $this->logger->error(__FUNCTION__, $message); - } else { - $result = $client->call($this->callFunction, $this->data); - $this->logger->debug(__FUNCTION__, 'Result from Endpoint: ', $result); - if ($this->fieldResult) { - if (isset($result[$this->fieldResult])) { - $this->logger->debug(__FUNCTION__, 'Output Result: ', $result[$this->fieldResult]); - $message = array( - 'status' => self::FIELD_FOUND_OR_FULL, - 'code' => $result[$this->fieldResult], - 'data' => $result - ); - } else { - $this->logger->debug(__FUNCTION__, 'Missing Result from ' . $this->fieldResult); - $message = array( - 'status' => self::FIELD_NOT_FOUND, - 'code' => 'Missing Result from ' . $this->fieldResult, - 'data' => $result - ); - } - } else { - $message = array( - 'status' => self::FIELD_FOUND_OR_FULL, - 'code' => 'Return full Response', - 'data' => $result - ); - } - } - } catch (Exception $e) { - $message = array( - 'status' => self::EXCEPTION_FOUND, - 'code' => 'Exception Error', - 'data' => array( - 'File' => $e->getFile(), - 'Line' => $e->getLine(), - 'Code' => $e->getCode(), - 'Message' => $e->getMessage() - ) - ); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - } - if ($this->responseIsJson) { - $this->logger->debug(__FUNCTION__, 'Response is Json'); - $message = json_encode($message); - } - $this->logger->debug(__FUNCTION__, 'Final Result: ', $message); + return null; + } + try { + $client = new nusoap_client($this->endpoint, true); + $client->soap_defencoding = self::SOAP_ENCODING; + $client->xml_encoding = self::XML_ENCODING; + $client->decode_utf8 = self::DECODE_UTF8; + $error = $client->getError(); + if ($error) { + $message = "Client Request WSDL Error: " . json_encode($error); + $this->logger->error(__FUNCTION__, $message); + } else { + $result = $client->call($this->callFunction, $this->data); + $this->logger->debug(__FUNCTION__, 'Result from Endpoint: ', $result); + if ($this->fieldResult) { + if (isset($result[$this->fieldResult])) { + $this->logger->debug(__FUNCTION__, 'Output Result: ', $result[$this->fieldResult]); + $message = array( + 'status' => self::FIELD_FOUND_OR_FULL, + 'code' => $result[$this->fieldResult], + 'data' => $result + ); + } else { + $this->logger->debug(__FUNCTION__, 'Missing Result from ' . $this->fieldResult); + $message = array( + 'status' => self::FIELD_NOT_FOUND, + 'code' => 'Missing Result from ' . $this->fieldResult, + 'data' => $result + ); + } + } else { + $message = array( + 'status' => self::FIELD_FOUND_OR_FULL, + 'code' => 'Return full Response', + 'data' => $result + ); + } + } + } catch (Exception $e) { + $message = array( + 'status' => self::EXCEPTION_FOUND, + 'code' => 'Exception Error', + 'data' => array( + 'File' => $e->getFile(), + 'Line' => $e->getLine(), + 'Code' => $e->getCode(), + 'Message' => $e->getMessage() + ) + ); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + } + if ($this->responseIsJson) { + $this->logger->debug(__FUNCTION__, 'Response is Json'); + $message = json_encode($message); + } + $this->logger->debug(__FUNCTION__, 'Final Result: ', $message); - return $message; - } + return $message; + } - /** - * Function clientRequestSOAP - Hàm khởi tạo reques tới endpoint qua giao thức SOAP - * - * @return array|null|string Call to SOAP request and received Response from Server - * Return is Json String if set setResponseIsJson(true) - * Return Null if class nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not - * exists - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 11/10/18 11:15 - */ - public function clientRequestSOAP() - { - $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); - if (!class_exists(nusoap_client::class)) { - $this->logger->critical(__FUNCTION__, 'nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not exists'); + /** + * Function clientRequestSOAP - Hàm khởi tạo reques tới endpoint qua giao thức SOAP + * + * @return array|null|string Call to SOAP request and received Response from Server + * Return is Json String if set setResponseIsJson(true) + * Return Null if class nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not + * exists + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 11/10/18 11:15 + */ + public function clientRequestSOAP() + { + $this->logger->debug(__FUNCTION__, '/------------> ' . __FUNCTION__ . ' <------------\\'); + if (!class_exists(nusoap_client::class)) { + $this->logger->critical(__FUNCTION__, 'nguyenanhung\MyNuSOAP\nusoap_client is unavailable, class is not exists'); - return null; - } - try { - $client = new nusoap_client($this->endpoint, true); - $client->soap_defencoding = self::SOAP_ENCODING; - $client->xml_encoding = self::XML_ENCODING; - $client->decode_utf8 = self::DECODE_UTF8; - $error = $client->getError(); - if ($error) { - $message = "Client Request SOAP Error: " . json_encode($error); - $this->logger->error(__FUNCTION__, $message); - } else { - $result = $client->call($this->callFunction, $this->data); - $this->logger->debug(__FUNCTION__, 'Result from Endpoint: ', $result); - if ($this->fieldResult) { - if (isset($result[$this->fieldResult])) { - $this->logger->debug(__FUNCTION__, 'Output Result: ', $result[$this->fieldResult]); - $message = array( - 'status' => self::FIELD_FOUND_OR_FULL, - 'code' => $result[$this->fieldResult], - 'data' => $result - ); - } else { - $this->logger->debug(__FUNCTION__, 'Missing Result from ' . $this->fieldResult); - $message = array( - 'status' => self::FIELD_NOT_FOUND, - 'code' => 'Missing Result from ' . $this->fieldResult, - 'data' => $result - ); - } - } else { - $message = array( - 'status' => self::FIELD_FOUND_OR_FULL, - 'code' => 'Return full Response', - 'data' => $result - ); - } - } - } catch (Exception $e) { - $message = array( - 'status' => self::EXCEPTION_FOUND, - 'code' => 'Exception Error', - 'data' => array( - 'File' => $e->getFile(), - 'Line' => $e->getLine(), - 'Code' => $e->getCode(), - 'Message' => $e->getMessage() - ) - ); - $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); - $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); - } - if ($this->responseIsJson) { - $this->logger->debug(__FUNCTION__, 'Response is Json'); - $message = json_encode($message); - } - $this->logger->debug(__FUNCTION__, 'Final Result: ', $message); + return null; + } + try { + $client = new nusoap_client($this->endpoint, true); + $client->soap_defencoding = self::SOAP_ENCODING; + $client->xml_encoding = self::XML_ENCODING; + $client->decode_utf8 = self::DECODE_UTF8; + $error = $client->getError(); + if ($error) { + $message = "Client Request SOAP Error: " . json_encode($error); + $this->logger->error(__FUNCTION__, $message); + } else { + $result = $client->call($this->callFunction, $this->data); + $this->logger->debug(__FUNCTION__, 'Result from Endpoint: ', $result); + if ($this->fieldResult) { + if (isset($result[$this->fieldResult])) { + $this->logger->debug(__FUNCTION__, 'Output Result: ', $result[$this->fieldResult]); + $message = array( + 'status' => self::FIELD_FOUND_OR_FULL, + 'code' => $result[$this->fieldResult], + 'data' => $result + ); + } else { + $this->logger->debug(__FUNCTION__, 'Missing Result from ' . $this->fieldResult); + $message = array( + 'status' => self::FIELD_NOT_FOUND, + 'code' => 'Missing Result from ' . $this->fieldResult, + 'data' => $result + ); + } + } else { + $message = array( + 'status' => self::FIELD_FOUND_OR_FULL, + 'code' => 'Return full Response', + 'data' => $result + ); + } + } + } catch (Exception $e) { + $message = array( + 'status' => self::EXCEPTION_FOUND, + 'code' => 'Exception Error', + 'data' => array( + 'File' => $e->getFile(), + 'Line' => $e->getLine(), + 'Code' => $e->getCode(), + 'Message' => $e->getMessage() + ) + ); + $this->logger->error(__FUNCTION__, 'Error Message: ' . $e->getMessage()); + $this->logger->error(__FUNCTION__, 'Error Trace As String: ' . $e->getTraceAsString()); + } + if ($this->responseIsJson) { + $this->logger->debug(__FUNCTION__, 'Response is Json'); + $message = json_encode($message); + } + $this->logger->debug(__FUNCTION__, 'Final Result: ', $message); - return $message; - } + return $message; + } } diff --git a/src/Utils.php b/src/Utils.php index 89a9602..13554a2 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -18,285 +18,284 @@ */ class Utils { - /** - * Function httpStatus - * - * @param $num - * - * @return array - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 28:29 - */ - public static function httpStatus($num): array - { - $http = array( - 100 => 'HTTP/1.1 100 Continue', - 101 => 'HTTP/1.1 101 Switching Protocols', - 200 => 'HTTP/1.1 200 OK', - 201 => 'HTTP/1.1 201 Created', - 202 => 'HTTP/1.1 202 Accepted', - 203 => 'HTTP/1.1 203 Non-Authoritative Information', - 204 => 'HTTP/1.1 204 No Content', - 205 => 'HTTP/1.1 205 Reset Content', - 206 => 'HTTP/1.1 206 Partial Content', - 300 => 'HTTP/1.1 300 Multiple Choices', - 301 => 'HTTP/1.1 301 Moved Permanently', - 302 => 'HTTP/1.1 302 Found', - 303 => 'HTTP/1.1 303 See Other', - 304 => 'HTTP/1.1 304 Not Modified', - 305 => 'HTTP/1.1 305 Use Proxy', - 307 => 'HTTP/1.1 307 Temporary Redirect', - 400 => 'HTTP/1.1 400 Bad Request', - 401 => 'HTTP/1.1 401 Unauthorized', - 402 => 'HTTP/1.1 402 Payment Required', - 403 => 'HTTP/1.1 403 Forbidden', - 404 => 'HTTP/1.1 404 Not Found', - 405 => 'HTTP/1.1 405 Method Not Allowed', - 406 => 'HTTP/1.1 406 Not Acceptable', - 407 => 'HTTP/1.1 407 Proxy Authentication Required', - 408 => 'HTTP/1.1 408 Request Time-out', - 409 => 'HTTP/1.1 409 Conflict', - 410 => 'HTTP/1.1 410 Gone', - 411 => 'HTTP/1.1 411 Length Required', - 412 => 'HTTP/1.1 412 Precondition Failed', - 413 => 'HTTP/1.1 413 Request Entity Too Large', - 414 => 'HTTP/1.1 414 Request-URI Too Large', - 415 => 'HTTP/1.1 415 Unsupported Media Type', - 416 => 'HTTP/1.1 416 Requested Range Not Satisfiable', - 417 => 'HTTP/1.1 417 Expectation Failed', - 500 => 'HTTP/1.1 500 Internal Server Error', - 501 => 'HTTP/1.1 501 Not Implemented', - 502 => 'HTTP/1.1 502 Bad Gateway', - 503 => 'HTTP/1.1 503 Service Unavailable', - 504 => 'HTTP/1.1 504 Gateway Time-out', - 505 => 'HTTP/1.1 505 HTTP Version Not Supported' - ); - header($http[$num]); + /** + * Function httpStatus + * + * @param $num + * + * @return array + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 28:29 + */ + public static function httpStatus($num): array + { + $http = array( + 100 => 'HTTP/1.1 100 Continue', + 101 => 'HTTP/1.1 101 Switching Protocols', + 200 => 'HTTP/1.1 200 OK', + 201 => 'HTTP/1.1 201 Created', + 202 => 'HTTP/1.1 202 Accepted', + 203 => 'HTTP/1.1 203 Non-Authoritative Information', + 204 => 'HTTP/1.1 204 No Content', + 205 => 'HTTP/1.1 205 Reset Content', + 206 => 'HTTP/1.1 206 Partial Content', + 300 => 'HTTP/1.1 300 Multiple Choices', + 301 => 'HTTP/1.1 301 Moved Permanently', + 302 => 'HTTP/1.1 302 Found', + 303 => 'HTTP/1.1 303 See Other', + 304 => 'HTTP/1.1 304 Not Modified', + 305 => 'HTTP/1.1 305 Use Proxy', + 307 => 'HTTP/1.1 307 Temporary Redirect', + 400 => 'HTTP/1.1 400 Bad Request', + 401 => 'HTTP/1.1 401 Unauthorized', + 402 => 'HTTP/1.1 402 Payment Required', + 403 => 'HTTP/1.1 403 Forbidden', + 404 => 'HTTP/1.1 404 Not Found', + 405 => 'HTTP/1.1 405 Method Not Allowed', + 406 => 'HTTP/1.1 406 Not Acceptable', + 407 => 'HTTP/1.1 407 Proxy Authentication Required', + 408 => 'HTTP/1.1 408 Request Time-out', + 409 => 'HTTP/1.1 409 Conflict', + 410 => 'HTTP/1.1 410 Gone', + 411 => 'HTTP/1.1 411 Length Required', + 412 => 'HTTP/1.1 412 Precondition Failed', + 413 => 'HTTP/1.1 413 Request Entity Too Large', + 414 => 'HTTP/1.1 414 Request-URI Too Large', + 415 => 'HTTP/1.1 415 Unsupported Media Type', + 416 => 'HTTP/1.1 416 Requested Range Not Satisfiable', + 417 => 'HTTP/1.1 417 Expectation Failed', + 500 => 'HTTP/1.1 500 Internal Server Error', + 501 => 'HTTP/1.1 501 Not Implemented', + 502 => 'HTTP/1.1 502 Bad Gateway', + 503 => 'HTTP/1.1 503 Service Unavailable', + 504 => 'HTTP/1.1 504 Gateway Time-out', + 505 => 'HTTP/1.1 505 HTTP Version Not Supported' + ); + header($http[$num]); - return array( - 'code' => $num, - 'error' => $http[$num], - ); - } + return array( + 'code' => $num, + 'error' => $http[$num], + ); + } - /** - * Function getHost - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 28:34 - */ - public static function getHost(): string - { - $host = ''; - if (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && $host = $_SERVER['HTTP_X_FORWARDED_HOST']) { - $elements = explode(',', $host); - $host = trim(end($elements)); - } elseif (isset($_SERVER['HTTP_HOST']) && !$host = $_SERVER['HTTP_HOST']) { - if (isset($_SERVER['SERVER_NAME']) && !$host = $_SERVER['SERVER_NAME']) { - $host = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : ''; - } - } - // Remove port number from host - $host = preg_replace('/:\d+$/', '', $host); + /** + * Function getHost + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 28:34 + */ + public static function getHost(): string + { + $host = ''; + if (isset($_SERVER['HTTP_X_FORWARDED_HOST']) && $host = $_SERVER['HTTP_X_FORWARDED_HOST']) { + $elements = explode(',', $host); + $host = trim(end($elements)); + } elseif (isset($_SERVER['HTTP_HOST']) && !$host = $_SERVER['HTTP_HOST']) { + if (isset($_SERVER['SERVER_NAME']) && !$host = $_SERVER['SERVER_NAME']) { + $host = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : ''; + } + } + // Remove port number from host + $host = preg_replace('/:\d+$/', '', $host); - return trim($host); - } + return trim($host); + } - /** - * Function getBrowserLanguage - * - * @return false|string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 17:32 - */ - public static function getBrowserLanguage() - { - $language = ''; - if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { - $language = mb_substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); - } + /** + * Function getBrowserLanguage + * + * @return false|string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 17:32 + */ + public static function getBrowserLanguage() + { + $language = ''; + if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { + $language = mb_substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); + } - return $language; - } + return $language; + } - /** - * Function paddingWebsitePrefix - * - * @param $url - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 28:56 - */ - public static function paddingWebsitePrefix($url): string - { - if (mb_strpos($url, 'http') !== 0) { - $url = 'http://' . $url; - } + /** + * Function paddingWebsitePrefix + * + * @param $url + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 28:56 + */ + public static function paddingWebsitePrefix($url): string + { + if (mb_strpos($url, 'http') !== 0) { + $url = 'http://' . $url; + } - return $url; - } + return $url; + } - /** - * Function urlAddParam - * - * @param $url - * @param $paramString - * - * @return string - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 29:03 - */ - public static function urlAddParam($url, $paramString): string - { - // neu chua co dau ? - if (mb_strpos($url, '?') === false) { - $url .= '?'; - } + /** + * Function urlAddParam + * + * @param $url + * @param $paramString + * + * @return string + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 29:03 + */ + public static function urlAddParam($url, $paramString): string + { + // neu chua co dau ? + if (mb_strpos($url, '?') === false) { + $url .= '?'; + } - return $url . '&' . $paramString; - } + return $url . '&' . $paramString; + } - /** - * Function currentPageURL - * - * @return array|string|string[] - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 18:37 - */ - public static function currentPageURL() - { - $pageURL = 'http'; - if ($_SERVER["HTTPS"] === "on") { - $pageURL .= "s"; - } - $pageURL .= "://"; - $serverPort = $_SERVER["SERVER_PORT"]; - if ($serverPort !== 80) { - $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"]; - } else { - $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; - } + /** + * Function currentPageURL + * + * @return array|string|string[] + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 18:37 + */ + public static function currentPageURL() + { + $pageURL = 'http'; + if ($_SERVER["HTTPS"] === "on") { + $pageURL .= "s"; + } + $pageURL .= "://"; + $serverPort = $_SERVER["SERVER_PORT"]; + if ($serverPort !== 80) { + $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"]; + } else { + $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; + } - return str_replace(array('?live', '&live'), array('?', ''), $pageURL); - } + return str_replace(array('?live', '&live'), array('?', ''), $pageURL); + } - /** - * Hàm replace các ký tự dash thừa (double dash --> single dash, remove first and last dash in url) - * - * @param $url - * - * @return false|string|string[]|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 08/08/2020 29:22 - */ - public static function refineDashInUrl($url) - { - $url = preg_replace('/[-]+/', '-', $url); - if ($url[0] === '-') { - $url = mb_substr($url, 1); - } - if ($url[mb_strlen($url) - 1] === '-') { - $url = mb_substr($url, 0, -1); - } + /** + * Hàm replace các ký tự dash thừa (double dash --> single dash, remove first and last dash in url) + * + * @param $url + * + * @return false|string|string[]|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 08/08/2020 29:22 + */ + public static function refineDashInUrl($url) + { + $url = preg_replace('/[-]+/', '-', $url); + if ($url[0] === '-') { + $url = mb_substr($url, 1); + } + if ($url[mb_strlen($url) - 1] === '-') { + $url = mb_substr($url, 0, -1); + } - return $url; - } + return $url; + } - /** - * Function saveExternalFile - * - * @param $img - * @param $fullPath - * @param string $type - * @param bool $isUseCurl - * - * @return bool|int - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 19:21 - */ - public static function saveExternalFile($img, $fullPath, $type = 'image', bool $isUseCurl = true) - { - if ($isUseCurl) { - //$fullPath = urlencode($fullPath); - $ch = curl_init($img); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); - curl_setopt($ch, CURLOPT_TIMEOUT, 30); - $raw_data = curl_exec($ch); - curl_close($ch); - //check if return error (include html in output) - if (mb_strpos($raw_data, 'html') === false) { - $fp = fopen($fullPath, 'wb'); - if (!$fp) { - return false; - } + /** + * Function saveExternalFile + * + * @param $img + * @param $fullPath + * @param string $type + * @param bool $isUseCurl + * + * @return bool|int + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 19:21 + */ + public static function saveExternalFile($img, $fullPath, $type = 'image', bool $isUseCurl = true) + { + if ($isUseCurl) { + //$fullPath = urlencode($fullPath); + $ch = curl_init($img); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); + curl_setopt($ch, CURLOPT_TIMEOUT, 30); + $raw_data = curl_exec($ch); + curl_close($ch); + //check if return error (include html in output) + if (mb_strpos($raw_data, 'html') === false) { + $fp = fopen($fullPath, 'wb'); + if (!$fp) { + return false; + } - if (!empty($raw_data)) { - fwrite($fp, $raw_data); - fclose($fp); + if (!empty($raw_data)) { + fwrite($fp, $raw_data); + fclose($fp); - return true; - } - } + return true; + } + } - return false; - } - $file_headers = @get_headers($img); - if (mb_strpos($file_headers[0], '200') || mb_strpos($file_headers[0], '302') || mb_strpos($file_headers[0], '304')) { - return file_put_contents($fullPath, file_get_contents($img)); - } + return false; + } + $file_headers = @get_headers($img); + if (mb_strpos($file_headers[0], '200') || mb_strpos($file_headers[0], '302') || mb_strpos($file_headers[0], '304')) { + return file_put_contents($fullPath, file_get_contents($img)); + } - return false; - } + return false; + } - /** - * Function xssClean - * - * @param $data - * - * @return array|string|string[]|null - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 12:17 - */ - public static function xssClean($data) - { - // Fix &entity\n; - //$data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data); - $data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data); - $data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data); - $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8'); - // Remove any attribute starting with "on" or xmlns - $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data); - // Remove javascript: and vbscript: protocols - $data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data); - $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data); - $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data); - // Only works in IE: - $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data); - $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data); - $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data); - // Remove namespaced elements (we do not need them) - $data = preg_replace('#]*+>#i', '', $data); - do { - // Remove really unwanted tags - $old_data = $data; - $data = preg_replace('#]*+>#i', '', $data); - } - while ($old_data !== $data); + /** + * Function xssClean + * + * @param $data + * + * @return array|string|string[]|null + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 12:17 + */ + public static function xssClean($data) + { + // Fix &entity\n; + //$data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data); + $data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data); + $data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data); + $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8'); + // Remove any attribute starting with "on" or xmlns + $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data); + // Remove javascript: and vbscript: protocols + $data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data); + $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data); + $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data); + // Only works in IE: + $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data); + $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data); + $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data); + // Remove namespaced elements (we do not need them) + $data = preg_replace('#]*+>#i', '', $data); + do { + // Remove really unwanted tags + $old_data = $data; + $data = preg_replace('#]*+>#i', '', $data); + } while ($old_data !== $data); - // we are done... - return $data; - } + // we are done... + return $data; + } } diff --git a/src/Version.php b/src/Version.php index b48d71f..c0e0c27 100644 --- a/src/Version.php +++ b/src/Version.php @@ -19,16 +19,16 @@ */ trait Version { - /** - * Function getVersion - * - * @author: 713uk13m - * @time : 10/7/18 01:07 - * - * @return string - */ - public function getVersion(): string - { - return self::VERSION; - } + /** + * Function getVersion + * + * @return string + * @author: 713uk13m + * @time : 10/7/18 01:07 + * + */ + public function getVersion(): string + { + return self::VERSION; + } } diff --git a/test/functions.php b/test/functions.php index 46995aa..f0a8ec1 100644 --- a/test/functions.php +++ b/test/functions.php @@ -8,41 +8,41 @@ * Time: 02:47 */ if (!function_exists('testOutputWriteLnOnRequest')) { - /** - * Function testOutputWriteLnOnRequest - * - * @param mixed $name - * @param mixed $msg - * - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 30:31 - */ - function testOutputWriteLnOnRequest($name = '', $msg = '') - { - if (is_array($msg) || is_object($msg)) { - $msg = json_encode($msg); - } - echo $name . ' -> ' . $msg . PHP_EOL; - } + /** + * Function testOutputWriteLnOnRequest + * + * @param mixed $name + * @param mixed $msg + * + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 30:31 + */ + function testOutputWriteLnOnRequest($name = '', $msg = '') + { + if (is_array($msg) || is_object($msg)) { + $msg = json_encode($msg); + } + echo $name . ' -> ' . $msg . PHP_EOL; + } } if (!function_exists('testCreateParamsOnRequest')) { - /** - * Function testCreateParamsOnRequest - * - * @param string $method - * - * @return array - * @author : 713uk13m - * @copyright: 713uk13m - * @time : 09/20/2021 52:27 - */ - function testCreateParamsOnRequest(string $method = 'GET') - { - return array( - 'sdk' => 'HungNG Request', - 'method' => $method, - 'date' => date('Y-m-d H:i:s') - ); - } + /** + * Function testCreateParamsOnRequest + * + * @param string $method + * + * @return array + * @author : 713uk13m + * @copyright: 713uk13m + * @time : 09/20/2021 52:27 + */ + function testCreateParamsOnRequest(string $method = 'GET') + { + return array( + 'sdk' => 'HungNG Request', + 'method' => $method, + 'date' => date('Y-m-d H:i:s') + ); + } } diff --git a/test/testHelper.php b/test/testHelper.php index c9244bc..c72bf18 100644 --- a/test/testHelper.php +++ b/test/testHelper.php @@ -18,9 +18,9 @@ $url = 'https://httpbin.org'; testOutputWriteLnOnRequest( - 'Test GET Request', - sendSimpleRequest( - $url . '/get', - testCreateParamsOnRequest() - ) + 'Test GET Request', + sendSimpleRequest( + $url . '/get', + testCreateParamsOnRequest() + ) ); diff --git a/test/testRequest.php b/test/testRequest.php index 3d4983b..b8ed467 100644 --- a/test/testRequest.php +++ b/test/testRequest.php @@ -14,12 +14,12 @@ $loggerPath = dirname(__DIR__) . '/tmp'; -$request = new MyRequests(); -$request->debugStatus = true; -$request->debugLevel = 'info'; -$request->debugLoggerPath = dirname(__DIR__) . '/tmp'; +$request = new MyRequests(); +$request->debugStatus = true; +$request->debugLevel = 'info'; +$request->debugLoggerPath = dirname(__DIR__) . '/tmp'; $request->debugLoggerFilename = 'Log-' . date('Y-m-d') . '.log'; -$request->debugStatus = true; +$request->debugStatus = true; $request->__construct(); $url = 'https://httpbin.org'; @@ -28,6 +28,6 @@ // Test Request GET testOutputWriteLnOnRequest('Test GET Request', $request->sendRequest( - $url . '/get', - testCreateParamsOnRequest() + $url . '/get', + testCreateParamsOnRequest() )); diff --git a/test/testUtils.php b/test/testUtils.php index c56cd93..0c38c04 100644 --- a/test/testUtils.php +++ b/test/testUtils.php @@ -14,7 +14,7 @@ use nguyenanhung\MyRequests\Utils; $tmpFolder = dirname(__DIR__) . '/tmp'; -$utils = new Utils(); +$utils = new Utils(); testOutputWriteLnOnRequest('Utils HTTP Status with 200', $utils::httpStatus(200)); testOutputWriteLnOnRequest('Utils getHost', $utils::getHost());