CURL extension and api test command

This commit is contained in:
ftc
2023-05-18 22:15:55 +03:00
parent 696600086f
commit 4232800cb9
39 changed files with 13179 additions and 25 deletions
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace app\commands;
use Yii;
use yii\console\Controller;
class TestController extends Controller
{
public function actionIndex()
{
$client = new \app\components\ApiClient(Yii::$app->params['apiEndpoint']);
print_r($client->getVersion());
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace app\components;
use linslin\yii2\curl;
use Yii;
class ApiClient
{
private $url;
private $http_client;
public function __construct($url)
{
$this->url = $url;
$this->http_client = new curl\Curl();
}
private function sendRequest($path, $json = null, $method = 'get')
{
$url = $this->url . '/' . $path;
$this->http_client->reset();
$this->http_client->setOption(CURLOPT_TIMEOUT, 3600);
$this->http_client->setOption(CURLOPT_HTTPHEADER,
['Content-Type: application/json',
]);
if (!empty($json))
{
$this->http_client->setOption(CURLOPT_POSTFIELDS, $json);
}
$result = $this->http_client->$method($url);
if ($this->http_client->responseCode !== 200)
{
throw new \Exception("Call to ZM failed: " . $this->http_client->responseCode . "\n" . $result);
}
return $result;
}
public function getVersion()
{
return $this->sendRequest('host/getVersion.json');
}
}
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "yiisoft/yii2-app-basic",
"description": "Yii 2 Basic Project Template",
"name": "glade/cameras",
"description": "Glade Camera Monitoring System",
"keywords": ["yii2", "framework", "basic", "project template"],
"homepage": "https://www.yiiframework.com/",
"type": "project",
@@ -17,7 +17,8 @@
"php": ">=7.4.0",
"yiisoft/yii2": "~2.0.45",
"yiisoft/yii2-bootstrap5": "~2.0.2",
"yiisoft/yii2-symfonymailer": "~2.0.3"
"yiisoft/yii2-symfonymailer": "~2.0.3",
"linslin/yii2-curl": "^1.5"
},
"require-dev": {
"yiisoft/yii2-debug": "~2.1.0",
Generated
+57 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "9d0b53ee6ff938a3a3b4e7006374fb5c",
"content-hash": "6ddc279f4e12dfbcec4fabd13c7cbaa4",
"packages": [
{
"name": "bower-asset/bootstrap",
@@ -409,6 +409,62 @@
},
"time": "2022-09-18T07:06:19+00:00"
},
{
"name": "linslin/yii2-curl",
"version": "1.5.0",
"source": {
"type": "git",
"url": "https://github.com/linslin/Yii2-Curl.git",
"reference": "c180a1e5d5035d9dbe54d2cd3cd7fec87c0de764"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/linslin/Yii2-Curl/zipball/c180a1e5d5035d9dbe54d2cd3cd7fec87c0de764",
"reference": "c180a1e5d5035d9dbe54d2cd3cd7fec87c0de764",
"shasum": ""
},
"require": {
"ext-curl": "*",
"ext-json": "*",
"php": ">=7.2.0 <9.0",
"yiisoft/yii2": "^2.0.0"
},
"require-dev": {
"codeception/module-asserts": "^1.3",
"guzzlehttp/guzzle": ">=4.1.4 <7.0",
"mcustiel/phiremock": "^2.1",
"mcustiel/phiremock-codeception-extension": "^2.1",
"mcustiel/phiremock-codeception-module": "^1.1.2"
},
"type": "yii2-extension",
"autoload": {
"psr-4": {
"linslin\\yii2\\curl\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nils Gajsek",
"email": "info@linslin.org"
}
],
"description": "Easy and nice cURL extension with RESTful support for Yii2",
"keywords": [
" curl",
"extension",
"restful",
"yii2"
],
"support": {
"issues": "https://github.com/linslin/Yii2-Curl/issues",
"source": "https://github.com/linslin/Yii2-Curl/tree/1.5.0"
},
"time": "2021-02-20T10:10:56+00:00"
},
{
"name": "paragonie/random_compat",
"version": "v9.99.100",
+1
View File
@@ -4,4 +4,5 @@ return [
'adminEmail' => 'admin@example.com',
'senderEmail' => 'noreply@example.com',
'senderName' => 'Example.com mailer',
'apiEndpoint' => 'http://192.168.0.5:8800/zm/api',
];
+1 -1
View File
@@ -14,11 +14,11 @@ return array(
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'2cffec82183ee1cea088009cef9a6fc3' => $vendorDir . '/ezyang/htmlpurifier/library/HTMLPurifier.composer.php',
'7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php',
'25072dd6e2470089de65ae7bf11d3109' => $vendorDir . '/symfony/polyfill-php72/bootstrap.php',
'0d59ee240a4cd96ddbb4ff164fccea4d' => $vendorDir . '/symfony/polyfill-php73/bootstrap.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php',
'2cffec82183ee1cea088009cef9a6fc3' => $vendorDir . '/ezyang/htmlpurifier/library/HTMLPurifier.composer.php',
'f598d06aa772fa33d905e87be6398fb1' => $vendorDir . '/symfony/polyfill-intl-idn/bootstrap.php',
'e3b2795a8a512b6083af088fb53afe6c' => $vendorDir . '/codeception/codeception/functions.php',
'77e7c5c0b74965caa0fbb0a094b7713f' => $vendorDir . '/codeception/verify/src/Codeception/bootstrap.php',
+3 -2
View File
@@ -13,6 +13,7 @@ return array(
'yii\\composer\\' => array($vendorDir . '/yiisoft/yii2-composer'),
'yii\\bootstrap5\\' => array($vendorDir . '/yiisoft/yii2-bootstrap5/src'),
'yii\\' => array($vendorDir . '/yiisoft/yii2'),
'linslin\\yii2\\curl\\' => array($vendorDir . '/linslin/yii2-curl'),
'cebe\\markdown\\' => array($vendorDir . '/cebe/markdown'),
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Php73\\' => array($vendorDir . '/symfony/polyfill-php73'),
@@ -35,7 +36,7 @@ return array(
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Symfony\\Component\\BrowserKit\\' => array($vendorDir . '/symfony/browser-kit'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'PhpParser\\' => array($vendorDir . '/nikic/php-parser/lib/PhpParser'),
@@ -48,5 +49,5 @@ return array(
'DeepCopy\\' => array($vendorDir . '/myclabs/deep-copy/src/DeepCopy'),
'Codeception\\PHPUnit\\' => array($vendorDir . '/codeception/phpunit-wrapper/src'),
'Codeception\\Extension\\' => array($vendorDir . '/codeception/codeception/ext'),
'Codeception\\' => array($vendorDir . '/codeception/stub/src', $vendorDir . '/codeception/codeception/src/Codeception', $vendorDir . '/codeception/verify/src/Codeception'),
'Codeception\\' => array($vendorDir . '/codeception/codeception/src/Codeception', $vendorDir . '/codeception/stub/src', $vendorDir . '/codeception/verify/src/Codeception'),
);
+13 -5
View File
@@ -15,11 +15,11 @@ class ComposerStaticInitc501b52c18a78741dc0d2bdb0f412b76
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'2cffec82183ee1cea088009cef9a6fc3' => __DIR__ . '/..' . '/ezyang/htmlpurifier/library/HTMLPurifier.composer.php',
'7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php',
'25072dd6e2470089de65ae7bf11d3109' => __DIR__ . '/..' . '/symfony/polyfill-php72/bootstrap.php',
'0d59ee240a4cd96ddbb4ff164fccea4d' => __DIR__ . '/..' . '/symfony/polyfill-php73/bootstrap.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => __DIR__ . '/..' . '/symfony/string/Resources/functions.php',
'2cffec82183ee1cea088009cef9a6fc3' => __DIR__ . '/..' . '/ezyang/htmlpurifier/library/HTMLPurifier.composer.php',
'f598d06aa772fa33d905e87be6398fb1' => __DIR__ . '/..' . '/symfony/polyfill-intl-idn/bootstrap.php',
'e3b2795a8a512b6083af088fb53afe6c' => __DIR__ . '/..' . '/codeception/codeception/functions.php',
'77e7c5c0b74965caa0fbb0a094b7713f' => __DIR__ . '/..' . '/codeception/verify/src/Codeception/bootstrap.php',
@@ -36,6 +36,10 @@ class ComposerStaticInitc501b52c18a78741dc0d2bdb0f412b76
'yii\\bootstrap5\\' => 15,
'yii\\' => 4,
),
'l' =>
array (
'linslin\\yii2\\curl\\' => 18,
),
'c' =>
array (
'cebe\\markdown\\' => 14,
@@ -127,6 +131,10 @@ class ComposerStaticInitc501b52c18a78741dc0d2bdb0f412b76
array (
0 => __DIR__ . '/..' . '/yiisoft/yii2',
),
'linslin\\yii2\\curl\\' =>
array (
0 => __DIR__ . '/..' . '/linslin/yii2-curl',
),
'cebe\\markdown\\' =>
array (
0 => __DIR__ . '/..' . '/cebe/markdown',
@@ -217,8 +225,8 @@ class ComposerStaticInitc501b52c18a78741dc0d2bdb0f412b76
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-message/src',
1 => __DIR__ . '/..' . '/psr/http-factory/src',
0 => __DIR__ . '/..' . '/psr/http-factory/src',
1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\EventDispatcher\\' =>
array (
@@ -270,8 +278,8 @@ class ComposerStaticInitc501b52c18a78741dc0d2bdb0f412b76
),
'Codeception\\' =>
array (
0 => __DIR__ . '/..' . '/codeception/stub/src',
1 => __DIR__ . '/..' . '/codeception/codeception/src/Codeception',
0 => __DIR__ . '/..' . '/codeception/codeception/src/Codeception',
1 => __DIR__ . '/..' . '/codeception/stub/src',
2 => __DIR__ . '/..' . '/codeception/verify/src/Codeception',
),
);
+59
View File
@@ -1306,6 +1306,65 @@
],
"install-path": "../guzzlehttp/psr7"
},
{
"name": "linslin/yii2-curl",
"version": "1.5.0",
"version_normalized": "1.5.0.0",
"source": {
"type": "git",
"url": "https://github.com/linslin/Yii2-Curl.git",
"reference": "c180a1e5d5035d9dbe54d2cd3cd7fec87c0de764"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/linslin/Yii2-Curl/zipball/c180a1e5d5035d9dbe54d2cd3cd7fec87c0de764",
"reference": "c180a1e5d5035d9dbe54d2cd3cd7fec87c0de764",
"shasum": ""
},
"require": {
"ext-curl": "*",
"ext-json": "*",
"php": ">=7.2.0 <9.0",
"yiisoft/yii2": "^2.0.0"
},
"require-dev": {
"codeception/module-asserts": "^1.3",
"guzzlehttp/guzzle": ">=4.1.4 <7.0",
"mcustiel/phiremock": "^2.1",
"mcustiel/phiremock-codeception-extension": "^2.1",
"mcustiel/phiremock-codeception-module": "^1.1.2"
},
"time": "2021-02-20T10:10:56+00:00",
"type": "yii2-extension",
"installation-source": "dist",
"autoload": {
"psr-4": {
"linslin\\yii2\\curl\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nils Gajsek",
"email": "info@linslin.org"
}
],
"description": "Easy and nice cURL extension with RESTful support for Yii2",
"keywords": [
" curl",
"extension",
"restful",
"yii2"
],
"support": {
"issues": "https://github.com/linslin/Yii2-Curl/issues",
"source": "https://github.com/linslin/Yii2-Curl/tree/1.5.0"
},
"install-path": "../linslin/yii2-curl"
},
{
"name": "myclabs/deep-copy",
"version": "1.11.1",
+22 -13
View File
@@ -1,9 +1,9 @@
<?php return array(
'root' => array(
'name' => 'yiisoft/yii2-app-basic',
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => NULL,
'name' => 'glade/cameras',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '696600086fbb7a36f508f432eaf3dfade10a5a77',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
@@ -208,6 +208,15 @@
'aliases' => array(),
'dev_requirement' => true,
),
'glade/cameras' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '696600086fbb7a36f508f432eaf3dfade10a5a77',
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/psr7' => array(
'pretty_version' => '2.5.0',
'version' => '2.5.0.0',
@@ -217,6 +226,15 @@
'aliases' => array(),
'dev_requirement' => true,
),
'linslin/yii2-curl' => array(
'pretty_version' => '1.5.0',
'version' => '1.5.0.0',
'reference' => 'c180a1e5d5035d9dbe54d2cd3cd7fec87c0de764',
'type' => 'yii2-extension',
'install_path' => __DIR__ . '/../linslin/yii2-curl',
'aliases' => array(),
'dev_requirement' => false,
),
'myclabs/deep-copy' => array(
'pretty_version' => '1.11.1',
'version' => '1.11.1.0',
@@ -760,15 +778,6 @@
'aliases' => array(),
'dev_requirement' => false,
),
'yiisoft/yii2-app-basic' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => NULL,
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'yiisoft/yii2-bootstrap5' => array(
'pretty_version' => '2.0.4',
'version' => '2.0.4.0',
+2
View File
@@ -0,0 +1,2 @@
vendor/
build/logs
+19
View File
@@ -0,0 +1,19 @@
language: php
php:
- '7.2'
- '7.3'
- '7.4'
- '8.0.1'
branches:
only:
- master
- develop
install:
- composer update
script:
- XDEBUG_MODE=coverage vendor/bin/codecept run --coverage-xml ./../../build/logs/clover.xml
addons:
code_climate:
repo_token: 24b886eb6df6abd48cb812de2c20b9311d0444f30043bdf4d254116e5225ed84
after_success:
- vendor/bin/test-reporter
+797
View File
@@ -0,0 +1,797 @@
<?php
/**
* Yii2 cURL wrapper
* With RESTful support.
*
* @category Web-yii2
* @package yii2-curl
* @author Nils Gajsek <info@linslin.org>
* @copyright 2013-2017 Nils Gajsek <info@linslin.org>
* @license http://opensource.org/licenses/MIT MIT Public
* @version 1.3.0
* @link http://www.linslin.org
*
*/
namespace linslin\yii2\curl;
use Yii;
/**
* Class Curl
* @package linslin\yii2\curl
*/
class Curl
{
// ################################################ class vars // ################################################
/**
* @var string|boolean
* Holds response data right after sending a request.
*/
public $response = null;
/**
* @var null|integer
* Error code holder: https://curl.haxx.se/libcurl/c/libcurl-errors.html
*/
public $errorCode = null;
/**
* @var null|string
* Error text holder: http://php.net/manual/en/function.curl-strerror.php
*/
public $errorText = null;
/**
* @var integer HTTP-Status Code
* This value will hold HTTP-Status Code. False if request was not successful.
*/
public $responseCode = null;
/**
* @var string|null HTTP Response Charset
* (taken from Content-type header)
*/
public $responseCharset = null;
/**
* @var int HTTP Response Length
* (taken from Content-length header, or strlen() of downloaded content)
*/
public $responseLength = -1;
/**
* @var string|null HTTP Response Content Type
* (taken from Content-type header)
*/
public $responseType = null;
/**
* @var array|null HTTP Response headers
* Lists response header in an array if CURLOPT_HEADER is set to true.
*/
public $responseHeaders = null;
/**
* @var array HTTP-Status Code
* Custom options holder
*/
protected $_options = [];
/**
* @var array
* Hold array of get params to send with the request
*/
protected $_getParams = [];
/**
* @var array
* Hold array of post params to send with the request
*/
protected $_postParams = [];
/**
* @var resource|null
* Holds cURL-Handler
*/
public $curl = null;
/**
* @var string
* hold base URL
*/
protected $_baseUrl = '';
/**
* @var array default curl options
* Default curl options
*/
protected $_defaultOptions = [
CURLOPT_USERAGENT => 'Yii2-Curl-Agent',
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
];
// ############################################### class methods // ##############################################
/**
* Start performing GET-HTTP-Request
*
* @param string $url
* @param boolean $raw if response body contains JSON and should be decoded
*
* @return mixed
* @throws \Exception
*/
public function get($url, $raw = true)
{
$this->_baseUrl = $url;
return $this->_httpRequest('GET', $raw);
}
/**
* Start performing HEAD-HTTP-Request
*
* @param string $url
*
* @return mixed
* @throws \Exception
*/
public function head($url)
{
$this->_baseUrl = $url;
return $this->_httpRequest('HEAD');
}
/**
* Start performing POST-HTTP-Request
*
* @param string $url
* @param boolean $raw if response body contains JSON and should be decoded
*
* @return mixed
* @throws \Exception
*/
public function post($url, $raw = true)
{
$this->_baseUrl = $url;
return $this->_httpRequest('POST', $raw);
}
/**
* Start performing PUT-HTTP-Request
*
* @param string $url
* @param boolean $raw if response body contains JSON and should be decoded
*
* @return mixed
* @throws \Exception
*/
public function put($url, $raw = true)
{
$this->_baseUrl = $url;
return $this->_httpRequest('PUT', $raw);
}
/**
* Start performing PATCH-HTTP-Request
*
* @param string $url
* @param bool $raw if response body contains JSON and should be decoded
*
* @return mixed
* @throws \Exception
*/
public function patch($url, $raw = true)
{
$this->_baseUrl = $url;
$this->setHeaders([
'X-HTTP-Method-Override' => 'PATCH'
]);
return $this->_httpRequest('PATCH',$raw);
}
/**
* Start performing DELETE-HTTP-Request
*
* @param string $url
* @param boolean $raw if response body contains JSON and should be decoded
*
* @return mixed
* @throws \Exception
*/
public function delete($url, $raw = true)
{
$this->_baseUrl = $url;
return $this->_httpRequest('DELETE', $raw);
}
/**
* Start performing OPTIONS-HTTP-Request
*
* @param string $url
* @param bool $raw if response body contains JSON and should be decoded
*
* @return mixed
* @throws \Exception
*/
public function options($url, $raw = true)
{
$this->_baseUrl = $url;
return $this->_httpRequest('OPTIONS', $raw);
}
/**
* Set curl option
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function setOption($key, $value)
{
//set value
if (array_key_exists($key, $this->_defaultOptions) && $key !== CURLOPT_WRITEFUNCTION) {
$this->_defaultOptions[$key] = $value;
} else {
$this->_options[$key] = $value;
}
//return self
return $this;
}
/**
* Set get params
*
* @param array $params
* @return $this
*/
public function setGetParams($params)
{
if (is_array($params)) {
foreach ($params as $key => $value) {
$this->_getParams[$key] = $value;
}
}
//return self
return $this;
}
/**
* Set get params
*
* @param array $params
* @return $this
*/
public function setPostParams($params)
{
if (is_array($params)) {
$this->setOption(
CURLOPT_POSTFIELDS,
http_build_query($params)
);
}
//return self
return $this;
}
/**
* Set raw post data allows you to post any data format.
*
* @param mixed $data
* @return $this
*/
public function setRawPostData($data)
{
$this->setOption(
CURLOPT_POSTFIELDS,
$data
);
//return self
return $this;
}
/**
* Set get params
*
* @param string $data
* @return $this
*/
public function setRequestBody($data)
{
if (is_string($data)) {
$this->setOption(
CURLOPT_POSTFIELDS,
$data
);
}
//return self
return $this;
}
/**
* Get URL - return URL parsed with given params
*
* @return string The full URL with parsed get params
*/
public function getUrl()
{
if (Count($this->_getParams) > 0) {
return $this->_baseUrl.'?'.http_build_query($this->_getParams);
} else {
return $this->_baseUrl;
}
}
/**
* Set curl options
*
* @param array $options
*
* @return $this
*/
public function setOptions($options)
{
$this->_options = $options + $this->_options;
return $this;
}
/**
* Set multiple headers for request.
*
* @param array $headers
*
* @return $this
*/
public function setHeaders($headers)
{
if (is_array($headers)) {
//init
$parsedHeader = [];
//collect currently set headers
foreach ($this->getRequestHeaders() as $header => $value) {
array_push($parsedHeader, $header.':'.$value);
}
//parse header into right format key:value
foreach ($headers as $header => $value) {
array_push($parsedHeader, $header.':'.$value);
}
//set headers
$this->setOption(
CURLOPT_HTTPHEADER,
$parsedHeader
);
}
return $this;
}
/**
* Set a single header for request.
*
* @param string $header
* @param string $value
*
* @return $this
*/
public function setHeader($header, $value)
{
//init
$parsedHeader = [];
//collect currently set headers
foreach ($this->getRequestHeaders() as $headerToSet => $valueToSet) {
array_push($parsedHeader, $headerToSet.':'.$valueToSet);
}
//add override new header
if (strlen($header) > 0) {
array_push($parsedHeader, $header.':'.$value);
}
//set headers
$this->setOption(
CURLOPT_HTTPHEADER,
$parsedHeader
);
return $this;
}
/**
* Unset a single header.
*
* @param string $header
*
* @return $this
*/
public function unsetHeader($header)
{
//init
$parsedHeader = [];
//collect currently set headers and filter "unset" header param.
foreach ($this->getRequestHeaders() as $headerToSet => $valueToSet) {
if ($header !== $headerToSet) {
array_push($parsedHeader, $headerToSet.':'.$valueToSet);
}
}
//set headers
$this->setOption(
CURLOPT_HTTPHEADER,
$parsedHeader
);
return $this;
}
/**
* Get all request headers as key:value array
*
* @return array
*/
public function getRequestHeaders()
{
//Init
$requestHeaders = $this->getOption(CURLOPT_HTTPHEADER);
$parsedRequestHeaders = [];
if (is_array($requestHeaders)) {
foreach ($requestHeaders as $headerValue) {
list ($key, $value) = explode(':', $headerValue, 2);
$parsedRequestHeaders[$key] = $value;
}
}
return $parsedRequestHeaders;
}
/**
* Get specific request header as key:value array
*
* @param string $headerKey
*
* @return string|null
*/
public function getRequestHeader($headerKey)
{
//Init
$parsedRequestHeaders = $this->getRequestHeaders();
return isset($parsedRequestHeaders[$headerKey]) ? $parsedRequestHeaders[$headerKey] : null;
}
/**
* Unset a single curl option
*
* @param string $key
*
* @return $this
*/
public function unsetOption($key)
{
//reset a single option if its set already
if (isset($this->_options[$key])) {
unset($this->_options[$key]);
}
return $this;
}
/**
* Unset all curl option, excluding default options.
*
* @return $this
*/
public function unsetOptions()
{
//reset all options
if (isset($this->_options)) {
$this->_options = [];
}
return $this;
}
/**
* Total reset of options, responses, etc.
*
* @return $this
*/
public function reset()
{
if ($this->curl !== null) {
curl_close($this->curl); //stop curl
}
//reset all options
if (isset($this->_options)) {
$this->_options = [];
}
//reset response & status params
$this->curl = null;
$this->errorCode = null;
$this->response = null;
$this->responseCode = null;
$this->responseCharset = null;
$this->responseLength = -1;
$this->responseType = null;
$this->errorText = null;
$this->_postParams = [];
$this->_getParams = [];
return $this;
}
/**
* Return a single option
*
* @param string|integer $key
* @return mixed|boolean
*/
public function getOption($key)
{
//get merged options depends on default and user options
$mergesOptions = $this->getOptions();
//return value or false if key is not set.
return isset($mergesOptions[$key]) ? $mergesOptions[$key] : false;
}
/**
* Return merged curl options and keep keys!
*
* @return array
*/
public function getOptions()
{
return $this->_options + $this->_defaultOptions;
}
/**
* Get curl info according to http://php.net/manual/de/function.curl-getinfo.php
*
* @param null $opt
* @return array|mixed
*/
public function getInfo($opt = null)
{
if ($this->curl !== null && $opt === null) {
return curl_getinfo($this->curl);
} elseif ($this->curl !== null && $opt !== null) {
return curl_getinfo($this->curl, $opt);
} else {
return [];
}
}
/**
* Performs HTTP request
*
* @param string $method
* @param boolean $raw if response body contains JSON and should be decoded -> helper.
*
* @throws \Exception if request failed
*
* @return mixed
*/
protected function _httpRequest($method, $raw = false)
{
//set request type and writer function
$this->setOption(CURLOPT_CUSTOMREQUEST, strtoupper($method));
//check if method is head and set no body
if ($method === 'HEAD') {
$this->setOption(CURLOPT_NOBODY, true);
$this->unsetOption(CURLOPT_WRITEFUNCTION);
}
//setup error reporting and profiling
if (defined('YII_DEBUG') && YII_DEBUG) {
Yii::debug('Start sending cURL-Request: '.$this->getUrl().'\n', __METHOD__);
Yii::beginProfile($method.' '.$this->_baseUrl.'#'.md5(serialize($this->_getDebugData())), __METHOD__);
}
/**
* proceed curl
*/
$curlOptions = $this->getOptions();
$this->curl = curl_init($this->getUrl());
curl_setopt_array($this->curl, $curlOptions);
$response = curl_exec($this->curl);
//check if curl was successful
if ($response === false) {
//set error code
$this->errorCode = curl_errno($this->curl);
$this->errorText = curl_strerror($this->errorCode);
switch ($this->errorCode) {
// 7, 28 = timeout
case 7:
case 28:
$this->responseCode = 'timeout';
return false;
break;
default:
return false;
break;
}
}
//extract header / body data if CURLOPT_HEADER are set to true
if (isset($curlOptions[CURLOPT_HEADER]) && $curlOptions[CURLOPT_HEADER]) {
$this->response = $this->_extractCurlBody($response);
$this->responseHeaders = $this->_extractCurlHeaders($response);
} else {
$this->response = $response;
}
// Extract additional curl params
$this->_extractAdditionalCurlParameter();
//end yii debug profile
if (defined('YII_DEBUG') && YII_DEBUG) {
Yii::debug('End cURL-Request: '.$this->response, __METHOD__);
Yii::endProfile($method.' '.$this->getUrl().'#'.md5(serialize($this->_getDebugData())), __METHOD__);
}
//check responseCode and return data/status
if ($this->getOption(CURLOPT_CUSTOMREQUEST) === 'HEAD') {
return true;
} else {
$this->response = $raw ? $this->response : json_decode($this->response, true);
return $this->response;
}
}
/**
* Extract additional curl params protected class helper
*/
protected function _extractAdditionalCurlParameter ()
{
/**
* retrieve response code
*/
$this->responseCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
/**
* try extract response type & charset.
*/
$this->responseType = curl_getinfo($this->curl, CURLINFO_CONTENT_TYPE);
if (!is_null($this->responseType) && count(explode(';', $this->responseType)) > 1) {
list($this->responseType, $possibleCharset) = explode(';', $this->responseType);
//extract charset
if (preg_match('~^charset=(.+?)$~', trim($possibleCharset), $matches) && isset($matches[1])) {
$this->responseCharset = strtolower($matches[1]);
}
}
/**
* try extract response length
*/
$this->responseLength = curl_getinfo($this->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
if((int)$this->responseLength === -1) {
$this->responseLength = strlen($this->response);
}
}
/**
* Extract body curl data from response
*
* @param string $response
* @return string
*/
protected function _extractCurlBody ($response)
{
return substr($response, $this->getInfo(CURLINFO_HEADER_SIZE));
}
/**
* Extract header curl data from response
*
* @param string $response
* @return array
*/
protected function _extractCurlHeaders ($response)
{
//Init
$headers = [];
$headerText = substr($response, 0, strpos($response, "\r\n\r\n"));
foreach (explode("\r\n", $headerText) as $i => $line) {
if ($i === 0) {
$headers['http_code'] = $line;
} else {
list ($key, $value) = explode(':', $line, 2);
$headers[$key] = ltrim($value);
}
}
return $headers;
}
/**
* Collects debug data for serialize
* @return array|bool|mixed
*/
private function _getDebugData () {
$data = [];
if (is_array($this->getOption(CURLOPT_POSTFIELDS))) {
foreach ($this->getOption(CURLOPT_POSTFIELDS) as $key => $debugItem) {
if (is_array($debugItem)) {
$data[$key] = $debugItem;
} else if ($debugItem instanceof \CURLFile) {
$data[$key] = [
'name' => $debugItem->name,
'mime' => $debugItem->mime,
'postname' => $debugItem->postname,
];
} // more to come?
}
} else {
$data = $this->getOption(CURLOPT_POSTFIELDS);
}
return $data;
}
}
+309
View File
@@ -0,0 +1,309 @@
yii2-curl extension
===================
[![Latest Stable Version](https://poser.pugx.org/linslin/yii2-curl/v/stable)](https://packagist.org/packages/linslin/yii2-curl)
[![Latest Master Build](https://api.travis-ci.org/linslin/Yii2-Curl.svg?branch=master)](https://travis-ci.org/linslin/Yii2-Curl/builds)
[![Test Coverage](https://codeclimate.com/github/linslin/Yii2-Curl/badges/coverage.svg)](https://codeclimate.com/github/linslin/Yii2-Curl/coverage)
[![Total Downloads](https://poser.pugx.org/linslin/yii2-curl/downloads)](https://packagist.org/packages/linslin/yii2-curl)
[![License](https://poser.pugx.org/linslin/yii2-curl/license)](https://packagist.org/packages/linslin/yii2-curl)
Easy working cURL extension for Yii2, including RESTful support:
- POST
- GET
- HEAD
- PUT
- PATCH
- DELETE
- OPTIONS
Requirements
------------
- Yii2
- PHP >=7.2.0 || 8.0.1
- ext-curl, ext-json, and php-curl installed
Installation
------------
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
```bash
composer require --prefer-dist linslin/yii2-curl "*"
```
Usage
-----
Once the extension is installed, simply use it in your code. The following example shows you how to handling a simple GET Request.
```php
use linslin\yii2\curl;
$curl = new curl\Curl();
//get http://example.com/
$response = $curl->get('http://example.com/');
if ($curl->errorCode === null) {
echo $response;
} else {
// List of curl error codes here https://curl.haxx.se/libcurl/c/libcurl-errors.html
switch ($curl->errorCode) {
case 6:
//host unknown example
break;
}
}
```
```php
// GET request with GET params
// http://example.com/?key=value&scondKey=secondValue
$curl = new curl\Curl();
$response = $curl->setGetParams([
'key' => 'value',
'secondKey' => 'secondValue'
])
->get('http://example.com/');
```
```php
// POST URL form-urlencoded
$curl = new curl\Curl();
$response = $curl->setPostParams([
'key' => 'value',
'secondKey' => 'secondValue'
])
->post('http://example.com/');
```
```php
// POST RAW JSON
$curl = new curl\Curl();
$response = $curl->setRawPostData(
json_encode[
'key' => 'value',
'secondKey' => 'secondValue'
])
->post('http://example.com/');
```
```php
// POST RAW JSON and auto decode JSON respawn by setting raw = true.
// This is usefull if you expect an JSON response and want to autoparse it.
$curl = new curl\Curl();
$response = $curl->setRawPostData(
json_encode[
'key' => 'value',
'secondKey' => 'secondValue'
])
->post('http://example.com/', true);
// JSON decoded response by parsing raw = true in to ->post().
var_dump($response);
```
```php
// POST RAW XML
$curl = new curl\Curl();
$response = $curl->setRawPostData('<?xml version="1.0" encoding="UTF-8"?><someNode>Test</someNode>')
->post('http://example.com/');
```
```php
// POST with special headers
$curl = new curl\Curl();
$response = $curl->setPostParams([
'key' => 'value',
'secondKey' => 'secondValue'
])
->setHeaders([
'Custom-Header' => 'user-b'
])
->post('http://example.com/');
```
```php
// POST JSON with body string & special headers
$curl = new curl\Curl();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$response = $curl->setRequestBody(json_encode($params))
->setHeaders([
'Content-Type' => 'application/json',
'Content-Length' => strlen(json_encode($params))
])
->post('http://example.com/');
```
```php
// Avanced POST request with curl options & error handling
$curl = new curl\Curl();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$response = $curl->setRequestBody(json_encode($params))
->setOption(CURLOPT_ENCODING, 'gzip')
->post('http://example.com/');
// List of status codes here http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
switch ($curl->responseCode) {
case 'timeout':
//timeout error logic here
break;
case 200:
//success logic here
break;
case 404:
//404 Error logic here
break;
}
//list response headers
var_dump($curl->responseHeaders);
```
Testing
------------
- Run codeception tests with `vendor/bin/codecept run` in repository root dir.
Run codeception with clover report `XDEBUG_MODE=coverage vendor/bin/codecept run --coverage-xml ./../../build/logs/clover.xml`.
On windows run `vendor\bin\codecept.bat run`.
On windows with clover report run `vendor\bin\codecept.bat run --coverage-xml ./../../build/logs/clover.xml`.
Changelog
------------
------------
##### Release 1.5.0 - Changelog
- Added PHP 8 support.
- Updated phiremock to v2.
- Removed not needed dependencies from the composer package file (https://github.com/linslin/Yii2-Curl/issues/88).
- Fixed CURLFile object serialization for profiling (https://github.com/linslin/Yii2-Curl/issues/87).
##### Release 1.4.0 - Changelog
- Added support for HTTP-Method OPTIONS.
- Removed deprecated PHP Version support. Minimum PHP Version is now 7.2.0.
Please use version "linslin/yii2-curl 1.3.0" - https://github.com/linslin/Yii2-Curl/releases/tag/1.3.0 if you need PHP 7.1.0+ support.
##### Release 1.3.0 - Changelog
- Fixed HTTP-Method parsing on PATCH request.
- Updated DocBlocks + code refactoring.
- Removed deprecated PHP Version support. Minimum PHP Version is now 7.1.3.
Please use version "linslin/yii2-curl 1.2.1" - https://github.com/linslin/Yii2-Curl/releases/tag/1.2.1 if you need PHP 5.4+ support.
##### Release 1.2.2 - Changelog
- Added some new cURL examples into readme.md.
##### Release 1.2.1 - Changelog
- Added `setRawPostData([mixed]) [this]` which allows you to post any data format.
##### Release 1.2.0 - Changelog
- Added `unsetHeader([string header]) [this]` helper which allows you to unset one specific header.
- Added `setHeader([string header, string value]) [this]` helper which allows you to set one specific header.
- Added `getRequestHeaders() [array]` helper which returns all request headers as an array.
- Added `getRequestHeader([string headerKey]) [string|null]` helper which returns a specific request header as an string.
- Added new test cases for `getRequestHeaders()` and `getRequestHeader()`.
- Readme adjustments.
##### Release 1.1.3 - Changelog
- Fixed issue with patch request.
- Fully added functionalTests for 100% coverage.
##### Release 1.1.2 - Changelog
- Fixed https://github.com/linslin/Yii2-Curl/issues/59
- Fixed https://github.com/linslin/Yii2-Curl/issues/57
##### Release 1.1.1 - Changelog
- Fixed wrong parameter parsing into `_httpRequest()` (thanks to yemexx1)
- Added JSON decode functions tests (thanks to yemexx1)
##### Release 1.1.0 - Changelog
- Added `setHeaders() [array]` helper.
- Added `setPostParams() [array]` helper.
- Added `setGetParams() [array]` helper.
- Added `setRequestBody() [string]` helper.
- Added `getUrl()` helper.
- Added API attribute `errorText [string|null]` - holds a string describing the given error code - https://github.com/linslin/Yii2-Curl/issues/49.
- Added functionTests to ensure stability.
- Allow PHP class goodness - https://github.com/linslin/Yii2-Curl/issues/52.
- Fixed header explode - https://github.com/linslin/Yii2-Curl/pull/51.
##### Release 1.0.11 - Changelog
- Added API attribute `responseHeaders [array|null]` which returns an array of all response headers.
- Changed `_defaultOptions[CURLOPT_HEADER]` to `true`.
- Profile debugging is only active if constant `YII_DEBUG` is `true`.
##### Release 1.0.10 - Changelog
- Fixed PHP notice https://github.com/linslin/Yii2-Curl/issues/39.
##### Release 1.0.9 - Changelog
- Added API attribute `responseCode [string|null]` which holds the HTTP response code.
- Added API attribute `responseCharset [string|null]` which holds the response charset.
- Added API attribute `responseLength [integer|null]` which holds the response length.
- Added API attribute `errorCode` which holds the a integer code error like described here: https://curl.haxx.se/libcurl/c/libcurl-errors.html.
- Fixed Issue https://github.com/linslin/Yii2-Curl/issues//36.
- Fixed Issue https://github.com/linslin/Yii2-Curl/issues//37 and removed exception throwing on curl fail. This allow the user to handle the error while using attribute `errorCode`.
##### Release 1.0.8 - Changelog
- Added API method `setOptions([array])` which allows to setup multiple options at once.
- Fixed Issue https://github.com/linslin/Yii2-Curl/issues/30.
##### Release 1.0.7 - Changelog
- Fixed `getInfo([, int $opt = 0 ])` exception were cURL wasn't initialized before calling `getInfo($opt)`.
##### Release 1.0.6 - Changelog
- Added `getInfo([, int $opt = 0 ])` method to retrieve http://php.net/manual/de/function.curl-getinfo.php data.
##### Release 1.0.5 - Changelog
- Made `body` callback not depending on HTTP-Status codes anymore. You can retrieve `body` data on any HTTP-Status now.
- Fixed Issue https://github.com/linslin/Yii2-Curl/issues/19 where override default settings break options.
- Added timeout response handling. `$curl->responseCode = 'timeout'`
##### Release 1.0.4 - Changelog
- `CURLOPT_RETURNTRANSFER` is now set to true on default - https://github.com/linslin/Yii2-Curl/issues/18
- Readme.md adjustments.
##### Release 1.0.3 - Changelog
- Fixed override of user options. https://github.com/linslin/Yii2-Curl/pull/7
- Nice formatted PHP-examples.
- Moved `parent::init();` behavior into unitTest Controller.
##### Release 1.0.2 - Changelog
- Added custom params support
- Added custom status code support
- Added POST-Param support and a readme example
- Removed "body" support at request functions. Please use "CURLOPT_POSTFIELDS" to setup a body now.
- Readme modifications
##### Release 1.0.1 - Changelog
- Removed widget support
- Edited some spellings + added more examples into readme.md
##### Release 1.0 - Changelog
- Official stable release
Thanks to
------------
------------
Mariano Custiel ([@mcustiel](https://github.com/mcustiel))
... and all other contributors.
+34
View File
@@ -0,0 +1,34 @@
actor: Tester
paths:
tests: tests
log: tests/_output
data: tests/_data
support: tests/_support
envs: tests/_envs
coverage:
enabled: true
include:
- Curl.php
bootstrap: _bootstrap.php
settings:
colors: true
memory_limit: 1024M
extensions:
enabled:
- \Codeception\Extension\Phiremock
- \Codeception\Extension\RunFailed
config:
\Codeception\Extension\Phiremock:
listen: 127.0.0.1:18080 # defaults to 0.0.0.0:8086
bin_path: vendor/bin # defaults to codeception_dir/../vendor/bin
debug: true # defaults to false
start_delay: 1 # default to 0
suites:
- unit
- acceptance
- functional
modules:
enabled:
- Phiremock:
host: 127.0.0.1 # Defaults to localhost
port: 18080 # Defaults to 8086
+42
View File
@@ -0,0 +1,42 @@
{
"name": "linslin/yii2-curl",
"description": "Easy and nice cURL extension with RESTful support for Yii2",
"type": "yii2-extension",
"keywords": ["yii2","extension"," curl", "RESTful"],
"license": "MIT",
"authors": [
{
"name": "Nils Gajsek",
"email": "info@linslin.org"
}
],
"require": {
"php": ">=7.2.0 <9.0",
"ext-json": "*",
"ext-curl": "*",
"yiisoft/yii2": "^2.0.0"
},
"require-dev": {
"guzzlehttp/guzzle": ">=4.1.4 <7.0",
"mcustiel/phiremock": "^2.1",
"mcustiel/phiremock-codeception-extension": "^2.1",
"mcustiel/phiremock-codeception-module": "^1.1.2",
"codeception/module-asserts": "^1.3"
},
"autoload": {
"psr-4": {
"linslin\\yii2\\curl\\": ""
}
},
"archive": {
"exclude": [
"/tests"
]
},
"repositories": [
{
"type": "composer",
"url": "https://asset-packagist.org"
}
]
}
+6129
View File
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
<?php
/**
* Minimal Yii2 setup for test environment
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
@@ -0,0 +1,2 @@
*
!.gitignore
@@ -0,0 +1,2 @@
*
!.gitignore
@@ -0,0 +1,2 @@
*
!.gitignore
@@ -0,0 +1,26 @@
<?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;
/**
* Define custom actions here
*/
}
@@ -0,0 +1,26 @@
<?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class FunctionalTester extends \Codeception\Actor
{
use _generated\FunctionalTesterActions;
/**
* Define custom actions here
*/
}
@@ -0,0 +1,10 @@
<?php
namespace Helper;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class Acceptance extends \Codeception\Module
{
}
@@ -0,0 +1,10 @@
<?php
namespace Helper;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class Functional extends \Codeception\Module
{
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace Helper;
// here you can define custom actions
// all public methods declared in helper class will be available in $I
class Unit extends \Codeception\Module
{
}
+26
View File
@@ -0,0 +1,26 @@
<?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class UnitTester extends \Codeception\Actor
{
use _generated\UnitTesterActions;
/**
* Define custom actions here
*/
}
@@ -0,0 +1,137 @@
<?php //[STAMP] cd097b21cd42b05db2fee563f9ee2b21
namespace _generated;
// This class was automatically generated by build task
// You should not change it manually as it will be overwritten on next build
// @codingStandardsIgnoreFile
trait AcceptanceTesterActions
{
/**
* @return \Codeception\Scenario
*/
abstract protected function getScenario();
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
@throws ModuleException
* @see \Codeception\Module\Phiremock::takeConnection()
*/
public function takeConnection($name): \Codeception\Module\Phiremock {
return $this->getScenario()->runStep(new \Codeception\Step\Action('takeConnection', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
@throws ClientExceptionInterface
* @see \Codeception\Module\Phiremock::expectARequestToRemoteServiceWithAResponse()
*/
public function expectARequestToRemoteServiceWithAResponse($expectation): void {
$this->getScenario()->runStep(new \Codeception\Step\Action('expectARequestToRemoteServiceWithAResponse', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
@throws ClientExceptionInterface
* @see \Codeception\Module\Phiremock::haveACleanSetupInRemoteService()
*/
public function haveACleanSetupInRemoteService(): void {
$this->getScenario()->runStep(new \Codeception\Step\Action('haveACleanSetupInRemoteService', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
@throws ClientExceptionInterface
* @see \Codeception\Module\Phiremock::dontExpectRequestsInRemoteService()
*/
public function dontExpectRequestsInRemoteService(): void {
$this->getScenario()->runStep(new \Codeception\Step\Action('dontExpectRequestsInRemoteService', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
@throws ClientExceptionInterface
* @see \Codeception\Module\Phiremock::haveCleanScenariosInRemoteService()
*/
public function haveCleanScenariosInRemoteService(): void {
$this->getScenario()->runStep(new \Codeception\Step\Action('haveCleanScenariosInRemoteService', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @deprecated Name is confusing, sounds like an assertion
* @throws ClientExceptionInterface
* @see \Codeception\Module\Phiremock::didNotReceiveRequestsInRemoteService()
*/
public function didNotReceiveRequestsInRemoteService(): void {
$this->getScenario()->runStep(new \Codeception\Step\Action('didNotReceiveRequestsInRemoteService', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
@throws ClientExceptionInterface
* @see \Codeception\Module\Phiremock::dontHaveLoggedRequestsToRemoteService()
*/
public function dontHaveLoggedRequestsToRemoteService(): void {
$this->getScenario()->runStep(new \Codeception\Step\Action('dontHaveLoggedRequestsToRemoteService', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @throws ClientExceptionInterface
* @throws Exception
* @see \Codeception\Module\Phiremock::seeRemoteServiceReceived()
*/
public function seeRemoteServiceReceived($times, $builder): void {
$this->getScenario()->runStep(new \Codeception\Step\Assertion('seeRemoteServiceReceived', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* [!] Conditional Assertion: Test won't be stopped on fail
* @throws ClientExceptionInterface
* @throws Exception
* @see \Codeception\Module\Phiremock::seeRemoteServiceReceived()
*/
public function canSeeRemoteServiceReceived($times, $builder): void {
$this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeRemoteServiceReceived', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
@throws ClientExceptionInterface
* @see \Codeception\Module\Phiremock::grabRequestsMadeToRemoteService()
*/
public function grabRequestsMadeToRemoteService($builder): array {
return $this->getScenario()->runStep(new \Codeception\Step\Action('grabRequestsMadeToRemoteService', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
@throws ClientExceptionInterface
* @see \Codeception\Module\Phiremock::setScenarioState()
*/
public function setScenarioState($name, $state): void {
$this->getScenario()->runStep(new \Codeception\Step\Action('setScenarioState', func_get_args()));
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+10
View File
@@ -0,0 +1,10 @@
# Codeception Test Suite Configuration
#
# Suite for acceptance tests.
# Perform tests in browser using the WebDriver or PhpBrowser.
# If you need both WebDriver and PHPBrowser tests - create a separate suite.
class_name: AcceptanceTester
modules:
enabled:
- \Helper\Acceptance
@@ -0,0 +1,2 @@
<?php
// Here you can initialize variables that will be available to your tests
+16
View File
@@ -0,0 +1,16 @@
# Codeception Test Suite Configuration
#
# Suite for functional (integration) tests
# Emulate web requests and make application process them
# Include one of framework modules (Symfony2, Yii2, Laravel5) to use it
class_name: FunctionalTester
modules:
enabled:
# add framework module here
- \Helper\Functional
- Asserts
- Phiremock:
host: 127.0.0.1
port: 18080
@@ -0,0 +1,2 @@
<?php
// Here you can initialize variables that will be available to your tests
@@ -0,0 +1,950 @@
<?php
//use namespaces
use Mcustiel\Phiremock\Client\Phiremock;
use Mcustiel\Phiremock\Client\Utils\A;
use Mcustiel\Phiremock\Client\Utils\Respond;
use Mcustiel\Phiremock\Client\Utils\Is;
/**
* Class httpMockCest
*/
class httpMockCest
{
// ############################################### private class vars // ###########################################
/**
* Holds instance of yii2-curl
* @type linslin\yii2\curl\Curl
*/
private $_curl = null;
/**
* Default test server endpoint URL
* @type string
*/
private $_endPoint = 'http://127.0.0.1:18080';
// ################################################## class methods // #############################################
/**
* Cleanup
* @param \FunctionalTester $I
*/
public function _before(\FunctionalTester $I)
{
$I->haveACleanSetupInRemoteService();
//Init curl
$this->_curl = new linslin\yii2\curl\Curl();
}
/**
* Simple HTTP ok
* @param FunctionalTester $I
* @throws Exception
*/
public function simpleHttpOkTest(\FunctionalTester $I)
{
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/httpStatus/200'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->get($this->_endPoint . '/test/httpStatus/200');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Try set params to send with get request
* @param FunctionalTester $I
* @throws Exception
*/
public function setGetParamsTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/params/get?' . http_build_query($params)))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setGetParams($params)
->get($this->_endPoint . '/test/params/get');
$I->assertEquals($this->_curl->responseCode, 200);
$I->assertEquals($this->_curl->getUrl(), $this->_endPoint . '/test/params/get?' . http_build_query($params));
}
/**
* Try set post to send with post request
* @param FunctionalTester $I
* @throws Exception
*/
public function setPostParamsTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/x-www-form-urlencoded'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setPostParams($params)
->post($this->_endPoint . '/test/params/post');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Try set post to send with post request
* @param FunctionalTester $I
* @throws Exception
*/
public function setPostParamsOptionTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/x-www-form-urlencoded'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setOption(
CURLOPT_POSTFIELDS,
http_build_query($params))
->post($this->_endPoint . '/test/params/post');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Try set post param with header modification
* @param FunctionalTester $I
* @throws Exception
*/
public function setPostParamsWithHeaderTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/json'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setPostParams($params)
->setHeaders([
'Content-Type' => 'application/json'
])
->post($this->_endPoint . '/test/params/post');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Post JSON data test
* @param FunctionalTester $I
* @throws Exception
*/
public function postJsonTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(json_encode($params)))
->andHeader('content-type', Is::equalTo('application/json'))
)->then(
Respond::withStatusCode(200)
->andBody('{"id": 1, "description": "I am a resource"}')
)
);
$this->_curl->setRequestBody(json_encode($params))
->setHeaders([
'content-type' => 'application/json',
'content-length' => strlen(json_encode($params))
])
->post($this->_endPoint . '/test/params/post');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Get JSON response test
* @param FunctionalTester $I
* @throws Exception
*/
public function getWithDecodedJsonResponseTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/params/get/json'))
)->then(
Respond::withStatusCode(200)
->andBody('{"id": 1, "description": "I am a resource"}')
)
);
$jsonResponse = $this->_curl->get($this->_endPoint . '/test/params/get/json', false);
$I->assertEquals($this->_curl->responseCode, 200);
$I->assertArrayHasKey('id', $jsonResponse);
$I->assertArrayHasKey('description', $jsonResponse);
$I->assertEquals($jsonResponse['id'], 1);
$I->assertEquals($jsonResponse['description'], 'I am a resource');
}
/**
* Get JSON response test
* @param FunctionalTester $I
* @throws Exception
*/
public function getWithRawJsonResponseTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/params/get/json'))
)->then(
Respond::withStatusCode(200)
->andBody('{"id": 1, "description": "I am a resource"}')
)
);
$rawResponse = $this->_curl->get($this->_endPoint . '/test/params/get/json', true);
$I->assertEquals($this->_curl->responseCode, 200);
$I->assertEquals($rawResponse, '{"id": 1, "description": "I am a resource"}');
}
/**
* Get header params with special header separators in values
* @issue https://github.com/linslin/Yii2-Curl/issues/59
*
* @param FunctionalTester $I
* @throws Exception
*/
public function getHeaderParamWithSpecialHeaderSeparatorInValue(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/header'))
)->then(
Respond::withStatusCode(200)
->andHeader('param', 'value')
->andHeader('location', 'http://somelocation/')
)
);
$this->_curl->get($this->_endPoint . '/test/header');
$I->assertEquals($this->_curl->responseCode, 200);
$I->assertEquals($this->_curl->responseHeaders['location'], 'http://somelocation/');
$I->assertEquals($this->_curl->responseHeaders['param'], 'value');
}
/**
* Default head method test
* @param FunctionalTester $I
* @throws Exception
*/
public function defaultHeadMethodTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::headRequest()->andUrl(Is::equalTo('/test/head'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->head($this->_endPoint . '/test/head');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Default delete method test
* @param FunctionalTester $I
* @throws Exception
*/
public function defaultDeleteMethodTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::deleteRequest()->andUrl(Is::equalTo('/test/head'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->delete($this->_endPoint . '/test/head');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Default patch method test
* @param FunctionalTester $I
* @throws Exception
*/
public function defaultPatchMethodTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::patchRequest()->andUrl(Is::equalTo('/test/head'))
->andHeader('X-HTTP-Method-Override', Is::equalTo('PATCH'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->patch($this->_endPoint . '/test/head');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Default put method test
* @param FunctionalTester $I
* @throws Exception
*/
public function defaultPutMethodTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::putRequest()->andUrl(Is::equalTo('/test/head'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->put($this->_endPoint . '/test/head');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Set single option test
* @param FunctionalTester $I
* @throws Exception
*/
public function setSingleDefaultOptionTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/x-www-form-urlencoded'))
->andHeader('user-agent', Is::equalTo('my-agent'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setOption(CURLOPT_USERAGENT, 'my-agent')
->setPostParams($params)
->post($this->_endPoint . '/test/params/post');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Set multiple option test
* @param FunctionalTester $I
* @throws Exception
*/
public function setMultipleOptionsTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/x-www-form-urlencoded'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setOptions([
CURLOPT_USERAGENT => 'my-agent',
CURLOPT_POSTFIELDS => http_build_query($params)
])
->post($this->_endPoint . '/test/params/post');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Set and unset option test
* @param FunctionalTester $I
* @throws Exception
*/
public function setUnsetSingleOptionTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(''))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setOption(CURLOPT_POSTFIELDS, http_build_query($params))
->unsetOption(CURLOPT_POSTFIELDS)
->post($this->_endPoint . '/test/params/post');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Set and unset all options test
* @param FunctionalTester $I
* @throws Exception
*/
public function setAllAndUnsertOptionsTest(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(''))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setOption(CURLOPT_POSTFIELDS, http_build_query($params))
->unsetOptions()
->post($this->_endPoint . '/test/params/post');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Simple reset after request test
* @param FunctionalTester $I
* @throws Exception
*/
public function resetAfterGet(\FunctionalTester $I)
{
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/httpStatus/200'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->get($this->_endPoint . '/test/httpStatus/200');
$I->assertEquals($this->_curl->responseCode, 200);
$this->_curl->reset();
$I->assertEquals($this->_curl->curl, null);
}
/**
* Simple get info test
* @param FunctionalTester $I
* @throws Exception
*/
public function getInfo(\FunctionalTester $I)
{
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/httpStatus/200'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->get($this->_endPoint . '/test/httpStatus/200');
$I->assertEquals($this->_curl->responseCode, 200);
$this->_curl->getInfo();
}
/**
* Simple get info without curl test
* @param \FunctionalTester $I
*/
public function getInfoWithoutCurl(\FunctionalTester $I)
{
$I->assertEquals($this->_curl->getInfo(CURLINFO_HEADER_SIZE ), []);
}
/**
* Simple curl timeout test
* @param FunctionalTester $I
* @throws Exception
*/
public function defaultCurlTimeoutError(\FunctionalTester $I)
{
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/httpStatus/timeout'))
)->then(
Respond::withStatusCode(404)
->andDelayInMillis(2000)
)
);
$this->_curl->setOption(CURLOPT_TIMEOUT, 1)
->get($this->_endPoint . '/test/httpStatus/timeout');
$I->assertEquals($this->_curl->responseCode, 'timeout');
}
/**
* Simple get without head request
* @param FunctionalTester $I
* @throws Exception
*/
public function simpleGetWithoutHead(\FunctionalTester $I)
{
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/httpStatus/200'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl
->setOption(CURLOPT_HEADER, false)
->get($this->_endPoint . '/test/httpStatus/200');
$I->assertEquals($this->_curl->responseCode, 200);
}
/**
* Simple curl error test CURL_UNSUPPORTED_PROTOCOL
* @param FunctionalTester $I
* @throws Exception
*/
public function defaultCurlError(\FunctionalTester $I)
{
$this->_curl->get( 'messy:/test/httpStatus/timeout');
$I->assertEquals($this->_curl->responseCode, null);
$I->assertLessOrEquals($this->_curl->errorCode, 1);
}
/**
* Default charset extract test
* @param FunctionalTester $I
* @throws Exception
*/
public function defaultCharsetExtractTest(\FunctionalTester $I)
{
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::getRequest()->andUrl(Is::equalTo('/test/httpStatus/header'))
)->then(
Respond::withStatusCode(200)
->andHeader('Content-Type', 'application/x-javascript;charset=UTF-8')
)
);
$this->_curl->get($this->_endPoint . '/test/httpStatus/header');
$I->assertEquals($this->_curl->responseCharset, 'utf-8');
}
/**
* Try set a header param and check if getHeaders() does return it
* @param FunctionalTester $I
* @throws Exception
*/
public function setHeaderParamAndTestGetHeaders(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/json'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setPostParams($params)
->setHeaders([
'Content-Type' => 'application/json'
])
->post($this->_endPoint . '/test/params/post');
//check for count
$I->assertEquals(count($this->_curl->getRequestHeaders()), 1);
//check for value
$requestHeaders = $this->_curl->getRequestHeaders();
$I->assertEquals($requestHeaders['Content-Type'], 'application/json');
}
/**
* Try set a header param and check if getHeader() does return it
* @param FunctionalTester $I
* @throws Exception
*/
public function setHeaderParamAndTestGetHeader(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/json'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setPostParams($params)
->setHeaders([
'Content-Type' => 'application/json'
])
->post($this->_endPoint . '/test/params/post');
//check for value
$I->assertEquals($this->_curl->getRequestHeader('Content-Type'), 'application/json');
}
/**
* Try set a single header param and check if getRequestHeader() does return it
* @param FunctionalTester $I
* @throws Exception
*/
public function setSingleHeaderParamAndTestGetHeader(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/json'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setPostParams($params)
->setHeader('Content-Type', 'application/json')
->post($this->_endPoint . '/test/params/post');
//check for value
$I->assertEquals($this->_curl->getRequestHeader('Content-Type'), 'application/json');
}
/**
* Try set a single header and multiple headers at once and check if getRequestHeader() does return it
* @param FunctionalTester $I
* @throws Exception
*/
public function setSingleHeaderAndMultipleHeadersAndTestGetHeader(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/json'))
->andHeader('custom-type', Is::equalTo('><)#7?aJEvgavJk(*4'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setPostParams($params)
->setHeader('Content-Type', 'application/json')
->setHeaders([
'custom-type' => '><)#7?aJEvgavJk(*4'
])
->post($this->_endPoint . '/test/params/post');
//check for value
$I->assertEquals($this->_curl->getRequestHeader('Content-Type'), 'application/json');
$I->assertEquals($this->_curl->getRequestHeader('custom-type'), '><)#7?aJEvgavJk(*4');
}
/**
* Try set a single header, multiple header and unset one header param and check if getRequestHeader() does return it
* @param FunctionalTester $I
* @throws Exception
*/
public function setSingleHeaderAndMultipleHeadersAndUnsetOneTillTestGetHeader(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/json'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setPostParams($params)
->setHeader('Content-Type', 'application/json')
->setHeaders([
'custom-type' => '><)#7?aJEvgavJk(*4'
])
->unsetHeader('custom-type')
->post($this->_endPoint . '/test/params/post');
//check for value
$I->assertEquals($this->_curl->getRequestHeader('Content-Type'), 'application/json');
$I->assertEquals($this->_curl->getRequestHeader('custom-type'), null);
}
/**
* Try set a single header, multiple header and unset one header param and check if getRequestHeader() does return it
* @param FunctionalTester $I
* @throws Exception
*/
public function setMultipleHeadersAndSingleHeaderAndUnsetOneTillTestGetHeader(\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(http_build_query($params)))
->andHeader('Content-Type', Is::equalTo('application/json'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setPostParams($params)
->setHeaders([
'custom-type' => '><)#7?aJEvgavJk(*4'
])
->setHeader('Content-Type', 'application/json')
->unsetHeader('custom-type')
->post($this->_endPoint . '/test/params/post');
//check for value
$I->assertEquals($this->_curl->getRequestHeader('Content-Type'), 'application/json');
$I->assertEquals($this->_curl->getRequestHeader('custom-type'), null);
}
/**
* Try to post raw json string
* @param FunctionalTester $I
* @throws Exception
*/
public function setRawPostDataTest (\FunctionalTester $I)
{
//Init
$this->_curl->reset();
$params = [
'key' => 'value',
'secondKey' => 'secondValue'
];
$I->expectARequestToRemoteServiceWithAResponse(
$expectation = Phiremock::on(
A::postRequest()->andUrl(Is::equalTo('/test/params/post'))
->andBody(Is::equalTo(json_encode($params)))
->andHeader('Content-Type', Is::equalTo('application/json'))
)->then(
Respond::withStatusCode(200)
)
);
$this->_curl->setRawPostData(json_encode($params))
->setHeader('Content-Type', 'application/json')
->post($this->_endPoint . '/test/params/post');
//check for value
$I->assertEquals($this->_curl->getRequestHeader('Content-Type'), 'application/json');
}
/**
* Simple HTTP ok
* @param FunctionalTester $I
* @throws Exception
*/
public function simpleOptionsOkTest(\FunctionalTester $I)
{
$I->expectARequestToRemoteServiceWithAResponse(
Phiremock::on(
A::optionsRequest()->andUrl(Is::equalTo('/test/httpStatus/204'))
)->then(
Respond::withStatusCode(204)
)
);
$this->_curl->options($this->_endPoint . '/test/httpStatus/204');
$I->assertEquals($this->_curl->responseCode, 204);
}
}
+9
View File
@@ -0,0 +1,9 @@
# Codeception Test Suite Configuration
#
# Suite for unit (internal) tests.
class_name: UnitTester
modules:
enabled:
- Asserts
- \Helper\Unit
+19
View File
@@ -0,0 +1,19 @@
<?php
/**
* Class CurlTest
*/
class CurlTest extends \Codeception\Test\Unit
{
// ################################################### Class methods ###############################################
/**
* No sense test
*/
public function testInit()
{
$curl = new linslin\yii2\curl\Curl();
$this->assertTrue($curl instanceof linslin\yii2\curl\Curl);
}
}
+2
View File
@@ -0,0 +1,2 @@
<?php
// Here you can initialize variables that will be available to your tests
+9
View File
@@ -49,4 +49,13 @@ return array (
'@yii/gii' => $vendorDir . '/yiisoft/yii2-gii/src',
),
),
'linslin/yii2-curl' =>
array (
'name' => 'linslin/yii2-curl',
'version' => '1.5.0.0',
'alias' =>
array (
'@linslin/yii2/curl' => $vendorDir . '/linslin/yii2-curl',
),
),
);