updated plugin `W3 Total Cache` version 2.3.3

This commit is contained in:
KawaiiPunk 2023-06-28 12:45:56 +00:00 committed by Gitium
parent 7d5eef77cf
commit aa3da0eb92
129 changed files with 17998 additions and 186 deletions

View File

@ -531,7 +531,11 @@ $keys = array(
),
'pgcache.accept.qs' => array(
'type' => 'array',
'default' => array()
'default' => \W3TC\PgCache_QsExempts::get_qs_exempts()
),
'pgcache.migrated.qsexempts' => array(
'type' => 'integer',
'default' => 0
),
'pgcache.late_init' => array(
'type' => 'boolean',

View File

@ -71,7 +71,7 @@ $engine = $config->get_string( array( 'fragmentcache', 'engine' ) );
<ul>
<?php
foreach ( $registered_groups as $group => $descriptor ) :
echo '<li>' . esc_html( $group ) . ' (' . esc_html( $descriptor['expiration'] ) . ' secs): ' . implode( ',', esc_html( $descriptor['actions'] ) ) . '</li>';
echo '<li>' . esc_html( $group ) . ' (' . esc_html( $descriptor['expiration'] ) . ' secs): ' . esc_html( implode( ',', $descriptor['actions'] ) ) . '</li>';
endforeach;
?>
</ul>

View File

@ -6,6 +6,7 @@ namespace W3TC;
*/
class Extension_FragmentCache_Plugin {
private $_config = null;
private $_core = null;
function __construct() {
$this->_config = Dispatcher::config();

View File

@ -273,6 +273,37 @@ class Generic_AdminActions_Default {
}
}
/**
* Page Cache tab
*/
if ( 'w3tc_pgcache' === $this->_page ) {
// Textarea settings.
$settings = array(
'pgcache.mirrors.home_urls',
'pgcache.purge.pages',
'pgcache.accept.qs',
'pgcache.reject.ua',
'pgcache.reject.cookie',
'pgcache.reject.uri',
'pgcache.reject.categories',
'pgcache.reject.tags',
'pgcache.reject.authors',
'pgcache.reject.custom',
'pgcache.accept.files',
'pgcache.accept.uri',
'pgcache.cache.headers',
);
// Remove empty lines, trim values, and sort.
foreach ( $settings as $setting ) {
$setting_array = $config->get_array( $setting );
if ( ! empty( $setting_array ) && is_array( $setting_array ) ) {
$values = array_filter( array_map( 'trim', $setting_array ), 'strlen' );
sort( $values );
$config->set( $setting, $values );
}
}
}
/**
* Minify tab
*/

View File

@ -399,6 +399,8 @@ class Generic_Plugin_Admin {
/**
* Define icon styles for the custom post type.
*
* @throws \Exception Exception.
*/
public function admin_head() {
global $wp_version;
@ -407,14 +409,27 @@ class Generic_Plugin_Admin {
$page = Util_Request::get_string( 'page', null );
if ( ( ! is_multisite() || is_super_admin() ) && false !== strpos( $page, 'w3tc' ) && 'w3tc_setup_guide' !== $page && ! get_site_option( 'w3tc_setupguide_completed' ) ) {
$config = new Config();
$state_master = Dispatcher::config_state_master();
if ( ! $config->get_boolean( 'pgcache.enabled' ) && $state_master->get_integer( 'common.install' ) > strtotime( 'NOW - 1 WEEK' ) ) {
if ( ! $this->_config->get_boolean( 'pgcache.enabled' ) && $state_master->get_integer( 'common.install' ) > strtotime( 'NOW - 1 WEEK' ) ) {
wp_safe_redirect( esc_url( network_admin_url( 'admin.php?page=w3tc_setup_guide' ) ) );
}
}
if ( empty( $this->_config->get_integer( 'pgcache.migrated.qsexempts' ) ) ) {
$pgcache_accept_qs = array_unique( array_merge( $this->_config->get_array( 'pgcache.accept.qs' ), PgCache_QsExempts::get_qs_exempts() ) );
sort( $pgcache_accept_qs );
$this->_config->set( 'pgcache.accept.qs', $pgcache_accept_qs );
$this->_config->set( 'pgcache.migrated.qsexempts', time() );
// Save the config if the environment is ready; filesystem needs to be writable.
try {
$this->_config->save();
} catch ( \Exception $e ) {
$this->_config->set( 'pgcache.migrated.qsexempts', null );
}
}
if ( 'w3tc_dashboard' === $page ) {
?>
<script type="text/javascript">

View File

@ -165,13 +165,13 @@ class Licensing_Plugin_Admin {
} elseif ( $this->_status_is( $status, 'inactive.expired' ) ) {
$message = wp_kses(
sprintf(
// translators: 1 HTML input button for renewing licence.
// translators: 1 HTML input button for renewing license.
__(
'It looks like your W3 Total Cache Pro License has expired. %1$s to continue using the Pro Features',
'It looks like your W3 Total Cache Pro license has expired. %1$s to continue using the Pro features',
'w3-total-cache'
),
'<input type="button" class="button-primary button-buy-plugin" data-nonce="' .
esc_url( wp_create_nonce( 'w3tc' ) ) . '" data-renew-key="' . esc_attr( $this->get_license_key() ) .
wp_create_nonce( 'w3tc' ) . '" data-renew-key="' . esc_attr( $this->get_license_key() ) .
'" data-src="licensing_expired" value="' . __( 'Renew Now', 'w3-total-cache' ) . '" />'
),
array(

View File

@ -2021,7 +2021,6 @@ class PgCache_ContentGrabber {
private function _normalize_querystring( $querystring ) {
$ignore_qs = $this->_config->get_array( 'pgcache.accept.qs' );
$ignore_qs = array_merge( $ignore_qs, PgCache_QsExempts::get_qs_exempts() );
$ignore_qs = w3tc_apply_filters( 'pagecache_extract_accept_qs', $ignore_qs );
Util_Rule::array_trim( $ignore_qs );

View File

@ -5,9 +5,19 @@ namespace W3TC;
class PgCache_Page extends Base_Page_Settings {
static public function admin_print_scripts_w3tc_pgcache() {
wp_enqueue_script( 'w3tc-options-validator',
plugins_url( 'pub/js/options-validator.js', W3TC_FILE ),
array(), W3TC_VERSION );
wp_enqueue_script( 'w3tc-options-validator', plugins_url( 'pub/js/options-validator.js', W3TC_FILE ), array(), W3TC_VERSION );
wp_register_script( 'w3tc-pgcache-qsexempts', plugins_url( 'PgCache_Page_View.js', W3TC_FILE ), array(), W3TC_VERSION, true );
wp_localize_script(
'w3tc-pgcache-qsexempts',
'W3TCPgCacheQsExemptsData',
array(
'defaultQsExempts' => PgCache_QsExempts::get_qs_exempts(),
)
);
wp_enqueue_script( 'w3tc-pgcache-qsexempts' );
}

View File

@ -0,0 +1,20 @@
/**
* File: PgCache_Page_View.js
*
* JavaScript for Page Cache settings page.
*
* @since 2.1.0
*
* @global W3TCPgCacheQsExemptsData
*/
jQuery(function() {
jQuery('.w3tc-pgcache-qsexempts-default').on(
'click',
function(){
var pgcacheQsExempts = jQuery('#pgcache_accept_qs').val().split("\n");
pgcacheQsExempts = pgcacheQsExempts.filter(item=>item).concat(W3TCPgCacheQsExemptsData.defaultQsExempts.filter((item)=>pgcacheQsExempts.indexOf(item)<0)).sort();
jQuery('#pgcache_accept_qs').val(pgcacheQsExempts.join("\n"));
}
);
});

View File

@ -20,7 +20,7 @@ if ( ! defined( 'W3TC' ) ) {
<?php Util_Ui::sealing_disabled( $module ); ?>
type="button" value="<?php esc_attr_e( 'Test', 'w3-total-cache' ); ?>" />
<span id="memcached_test_status" class="w3tc-status w3tc-process"></span>
<p class="description"><?php esc_html_e( 'Multiple servers may be used and seperated by a comma; e.g. 192.168.1.100:11211, domain.com:22122', 'w3-total-cache' ); ?></p>
<p class="description"><?php esc_html_e( 'Multiple servers may be used and seperated by a comma; e.g. 127.0.0.1:11211, domain.com:11211', 'w3-total-cache' ); ?></p>
</td>
</tr>
<tr>

View File

@ -22,7 +22,7 @@ $config = Dispatcher::config();
<?php Util_Ui::sealing_disabled( $module ); ?>
type="button" value="<?php esc_attr_e( 'Test', 'w3-total-cache' ); ?>" />
<span id="memcached_test_status" class="w3tc-status w3tc-process"></span>
<p class="description"><?php esc_html_e( 'Multiple servers may be used and seperated by a comma; e.g. 192.168.1.100:11211, domain.com:22122', 'w3-total-cache' ); ?></p>
<p class="description"><?php esc_html_e( 'Multiple servers may be used and seperated by a comma; e.g. 127.0.0.1:11211, domain.com:11211', 'w3-total-cache' ); ?></p>
</td>
</tr>
<?php

View File

@ -27,7 +27,7 @@ if ( ! defined( 'W3TC' ) ) {
<?php Util_Ui::sealing_disabled( $module ); ?>
type="button" value="<?php esc_attr_e( 'Test', 'w3-total-cache' ); ?>" />
<span class="w3tc_common_redis_test_result w3tc-status w3tc-process"></span>
<p class="description"><?php esc_html_e( 'Multiple servers may be used and seperated by a comma; e.g. 192.168.1.100:11211, domain.com:22122. To use TLS, prefix server with tls://', 'w3-total-cache' ); ?></p>
<p class="description"><?php esc_html_e( 'Multiple servers may be used and seperated by a comma; e.g. 127.0.0.1:6379, domain.com:6379. To use TLS, prefix server with tls://', 'w3-total-cache' ); ?></p>
</td>
</tr>
<?php

View File

@ -29,7 +29,7 @@ $config = Dispatcher::config();
<?php Util_Ui::sealing_disabled( $module ); ?>
type="button" value="<?php esc_attr_e( 'Test', 'w3-total-cache' ); ?>" />
<span class="w3tc_common_redis_test_result w3tc-status w3tc-process"></span>
<p class="description"><?php esc_html_e( 'Multiple servers may be used and seperated by a comma; e.g. 192.168.1.100:11211, domain.com:22122. To use TLS, prefix server with tls://', 'w3-total-cache' ); ?></p>
<p class="description"><?php esc_html_e( 'Multiple servers may be used and seperated by a comma; e.g. 127.0.0.1:6379, domain.com:6379. To use TLS, prefix server with tls://', 'w3-total-cache' ); ?></p>
</td>
</tr>
<?php

View File

@ -610,6 +610,7 @@ if ( ! defined( 'W3TC' ) ) {
<textarea id="pgcache_accept_qs" name="pgcache__accept__qs"
<?php Util_Ui::sealing_disabled( 'pgcache.' ); ?>
cols="40" rows="5"><?php echo esc_textarea( implode( "\r\n", $this->_config->get_array( 'pgcache.accept.qs' ) ) ); ?></textarea>
<input type="button" class="button w3tc-pgcache-qsexempts-default" value="Add Defaults" />
<p class="description">
<?php
echo wp_kses(

View File

@ -2,20 +2,20 @@
# This file is distributed under the GPL v2 or later.
msgid ""
msgstr ""
"Project-Id-Version: W3 Total Cache 2.3.0\n"
"Project-Id-Version: W3 Total Cache 2.3.3\n"
"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/w3-total-cache\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"POT-Creation-Date: 2023-03-21T21:21:22+00:00\n"
"POT-Creation-Date: 2023-06-19T14:09:34+00:00\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"X-Generator: WP-CLI 2.5.0\n"
"X-Domain: w3-total-cache\n"
#. Plugin Name of the plugin
#: Generic_Plugin_Admin.php:1056
#: Generic_Plugin_Admin.php:1071
#: SetupGuide_Plugin_Admin.php:1081
#: SetupGuide_Plugin_Admin.php:1127
#: SetupGuide_Plugin_Admin.php:1199
@ -498,7 +498,7 @@ msgstr ""
#: inc/options/minify.php:572
#: inc/options/minify.php:847
#: inc/options/minify.php:1025
#: inc/options/pgcache.php:829
#: inc/options/pgcache.php:830
msgid "Hypertext Transfer Protocol"
msgstr ""
@ -517,13 +517,13 @@ msgstr ""
#: BrowserCache_Page_View_SectionSecurity.php:758
#: BrowserCache_Page_View_SectionSecurity.php:948
#: BrowserCache_Page_View_SectionSecurity.php:1080
#: Generic_Plugin_Admin.php:864
#: Generic_Plugin_Admin.php:879
#: inc/options/browsercache.php:201
#: inc/options/browsercache.php:473
#: inc/options/browsercache.php:702
#: inc/options/pgcache.php:177
#: inc/options/pgcache.php:544
#: inc/options/pgcache.php:622
#: inc/options/pgcache.php:623
msgid "Uniform Resource Locator"
msgstr ""
@ -1322,7 +1322,7 @@ msgstr ""
#: Cdn_StackPath_Page_View.php:231
#: Cdn_StackPath_Widget_View_Unauthorized.php:16
#: Cdn_StackPath_Widget_View_Unauthorized.php:33
#: Generic_Plugin_Admin.php:956
#: Generic_Plugin_Admin.php:971
#: inc/lightbox/self_test.php:122
#: inc/lightbox/self_test.php:247
#: inc/lightbox/self_test.php:318
@ -1556,7 +1556,7 @@ msgstr ""
#: Cdn_StackPath_Widget_View_Unauthorized.php:16
#: Cdn_StackPath_Widget_View_Unauthorized.php:33
#: Extension_NewRelic_AdminNotes.php:23
#: Generic_Plugin_Admin.php:956
#: Generic_Plugin_Admin.php:971
#: PageSpeed_Instructions.php:383
#: PageSpeed_Instructions.php:397
#: PageSpeed_Instructions.php:579
@ -2407,8 +2407,8 @@ msgstr ""
#: inc/options/general.php:1049
#: inc/options/minify.php:169
#: inc/options/minify.php:195
#: inc/options/pgcache.php:831
#: inc/options/pgcache.php:860
#: inc/options/pgcache.php:832
#: inc/options/pgcache.php:861
msgid "Hypertext Markup Language"
msgstr ""
@ -3199,7 +3199,7 @@ msgstr ""
msgid "Database"
msgstr ""
#: DbCache_Plugin_Admin.php:61
#: DbCache_Plugin_Admin.php:64
msgid "Database Cache: %s."
msgstr ""
@ -4519,7 +4519,7 @@ msgstr ""
#: FeatureShowcase_Plugin_Admin.php:461
#: FeatureShowcase_Plugin_Admin.php:473
#: FeatureShowcase_Plugin_Admin.php:485
#: Generic_Plugin_Admin.php:737
#: Generic_Plugin_Admin.php:752
#: inc/options/extensions/list.php:102
msgid "Settings"
msgstr ""
@ -4687,7 +4687,7 @@ msgstr ""
#: inc/options/minify.php:363
#: inc/options/minify.php:383
#: Minify_ConfigLabels.php:9
#: Minify_Plugin.php:306
#: Minify_Plugin.php:310
#: Minify_Plugin_Admin.php:49
#: PageSpeed_Instructions.php:67
#: PageSpeed_Instructions.php:84
@ -5346,7 +5346,7 @@ msgstr ""
msgid "You do not have the rights to perform this action."
msgstr ""
#: Generic_AdminActions_Default.php:584
#: Generic_AdminActions_Default.php:615
msgid "Added by W3 Total Cache"
msgstr ""
@ -5354,23 +5354,23 @@ msgstr ""
msgid "Static files cache successfully emptied."
msgstr ""
#: Generic_AdminActions_Test.php:85
#: Generic_AdminActions_Test.php:88
msgid "Test passed."
msgstr ""
#: Generic_AdminActions_Test.php:90
#: Generic_AdminActions_Test.php:93
msgid "Test failed."
msgstr ""
#: Generic_AdminActions_Test.php:113
#: Generic_AdminActions_Test.php:116
msgid "Empty JAVA executable path."
msgstr ""
#: Generic_AdminActions_Test.php:115
#: Generic_AdminActions_Test.php:118
msgid "Empty JAR file path."
msgstr ""
#: Generic_AdminActions_Test.php:150
#: Generic_AdminActions_Test.php:153
msgid "Invalid engine."
msgstr ""
@ -5624,42 +5624,42 @@ msgid "Support Us"
msgstr ""
#. translators: 4: HTML line break tag, 5: HTML opening a tag to purge CDN manually, 6: HTML closing a tag.
#: Generic_Plugin_Admin.php:601
#: Generic_Plugin_Admin.php:616
msgid "Please see %1$sAmazon's CloudFront documentation -- Paying for file invalidation%2$sThe first 1,000 invalidation paths that you submit per month are free; you pay for each invalidation path over 1,000 in a month.%3$sYou can disable automatic purging by enabling %4$sOnly purge CDN manually%5$s."
msgstr ""
#: Generic_Plugin_Admin.php:738
#: Generic_Plugin_Admin.php:753
msgid "Premium Support"
msgstr ""
#: Generic_Plugin_Admin.php:759
#: Generic_Plugin_Admin.php:774
msgid "Empty Caches"
msgstr ""
#: Generic_Plugin_Admin.php:806
#: Generic_Plugin_Admin.php:821
msgid "Take a minute to update, here's why:"
msgstr ""
#. translators: 1 enable button link.
#: Generic_Plugin_Admin.php:843
#: Generic_Plugin_Admin.php:858
msgid "Fancy permalinks are disabled. Please %1$s it first, then re-attempt to enabling enhanced disk mode."
msgstr ""
#. translators: 1 enable button link.
#: Generic_Plugin_Admin.php:851
#: Generic_Plugin_Admin.php:866
msgid "Fancy permalinks are disabled. Please %1$s it first, then re-attempt to enabling the 'Do not process 404 errors for static objects with WordPress'."
msgstr ""
#: Generic_Plugin_Admin.php:857
#: Generic_Plugin_Admin.php:872
msgid "Please select request type."
msgstr ""
#. translators: 1 HTML acronym URL (uniform resource locator).
#: Generic_Plugin_Admin.php:860
#: Generic_Plugin_Admin.php:875
msgid "Please enter the address of the site in the site %1$s field."
msgstr ""
#: Generic_Plugin_Admin.php:864
#: Generic_Plugin_Admin.php:879
#: Util_PageSpeed.php:279
#: Util_PageSpeed.php:289
#: Util_PageSpeed.php:462
@ -5667,55 +5667,55 @@ msgstr ""
msgid "URL"
msgstr ""
#: Generic_Plugin_Admin.php:866
#: Generic_Plugin_Admin.php:881
msgid "Please enter your name in the Name field"
msgstr ""
#: Generic_Plugin_Admin.php:867
#: Generic_Plugin_Admin.php:882
msgid "Please enter valid email address in the E-Mail field."
msgstr ""
#: Generic_Plugin_Admin.php:868
#: Generic_Plugin_Admin.php:883
msgid "Please enter your phone in the phone field."
msgstr ""
#: Generic_Plugin_Admin.php:869
#: Generic_Plugin_Admin.php:884
msgid "Please enter subject in the subject field."
msgstr ""
#: Generic_Plugin_Admin.php:870
#: Generic_Plugin_Admin.php:885
msgid "Please describe the issue in the issue description field."
msgstr ""
#: Generic_Plugin_Admin.php:871
#: Generic_Plugin_Admin.php:886
msgid "Please enter an administrator login. Create a temporary one just for this support case if needed."
msgstr ""
#: Generic_Plugin_Admin.php:872
#: Generic_Plugin_Admin.php:887
msgid "Please enter WP Admin password, be sure it's spelled correctly."
msgstr ""
#. translators: 1 HTML acronym SSH (secure shell), 2 HTML acronym FTP (file transfer protocol).
#: Generic_Plugin_Admin.php:875
#: Generic_Plugin_Admin.php:890
msgid "Please enter %1$s or %2$s host for the site."
msgstr ""
#: Generic_Plugin_Admin.php:879
#: Generic_Plugin_Admin.php:888
#: Generic_Plugin_Admin.php:897
#: Generic_Plugin_Admin.php:894
#: Generic_Plugin_Admin.php:903
#: Generic_Plugin_Admin.php:912
#: inc/options/cdn/ftp.php:240
msgid "Secure Shell"
msgstr ""
#: Generic_Plugin_Admin.php:879
#: Generic_Plugin_Admin.php:888
#: Generic_Plugin_Admin.php:897
#: Generic_Plugin_Admin.php:894
#: Generic_Plugin_Admin.php:903
#: Generic_Plugin_Admin.php:912
msgid "SSH"
msgstr ""
#: Generic_Plugin_Admin.php:880
#: Generic_Plugin_Admin.php:889
#: Generic_Plugin_Admin.php:898
#: Generic_Plugin_Admin.php:895
#: Generic_Plugin_Admin.php:904
#: Generic_Plugin_Admin.php:913
#: inc/lightbox/self_test.php:120
#: inc/lightbox/self_test.php:316
#: inc/options/cdn/ftp.php:19
@ -5730,197 +5730,197 @@ msgstr ""
msgid "File Transfer Protocol"
msgstr ""
#: Generic_Plugin_Admin.php:880
#: Generic_Plugin_Admin.php:889
#: Generic_Plugin_Admin.php:898
#: Generic_Plugin_Admin.php:895
#: Generic_Plugin_Admin.php:904
#: Generic_Plugin_Admin.php:913
msgid "FTP"
msgstr ""
#. translators: 1 HTML acronym SSH (secure shell), 2 HTML acronym FTP (file transfer protocol).
#: Generic_Plugin_Admin.php:884
#: Generic_Plugin_Admin.php:899
msgid "Please enter %1$s or %2$s login for the server. Create a temporary one just for this support case if needed."
msgstr ""
#. translators: 1 HTML acronym SSH (secure shell), 2 HTML acronym FTP (file transfer protocol).
#: Generic_Plugin_Admin.php:893
#: Generic_Plugin_Admin.php:908
msgid "Please enter %1$s or %2$s password for the %2$s account."
msgstr ""
#: Generic_Plugin_Admin.php:900
#: Generic_Plugin_Admin.php:915
msgid "Unable to send the support request."
msgstr ""
#: Generic_Plugin_Admin.php:901
#: Generic_Plugin_Admin.php:916
msgid "Please select config file."
msgstr ""
#: Generic_Plugin_Admin.php:902
#: Generic_Plugin_Admin.php:917
msgid "Unable to upload config file."
msgstr ""
#: Generic_Plugin_Admin.php:903
#: Generic_Plugin_Admin.php:918
msgid "Configuration file could not be imported."
msgstr ""
#. translators: 1 W3TC config director path.
#: Generic_Plugin_Admin.php:906
#: Generic_Plugin_Admin.php:921
msgid "Default settings could not be restored. Please run %1$s to make the configuration file write-able, then try again."
msgstr ""
#: Generic_Plugin_Admin.php:912
#: Generic_Plugin_Admin.php:927
msgid "Unable to purge attachment."
msgstr ""
#: Generic_Plugin_Admin.php:913
#: Generic_Plugin_Admin.php:928
msgid "Unable to purge post."
msgstr ""
#. translators: 1 absolute path to wp-config.php, 2 cookie domain definition, 3 require once wp-setting.php definition.
#: Generic_Plugin_Admin.php:916
#: Generic_Plugin_Admin.php:931
msgid "%1$s could not be written, please edit config and add: %2$s before %3$s."
msgstr ""
#. translators: 1 absolute path to wp-config.php, 2 cooke domain definition, 3 require once wp-setting.php definition.
#: Generic_Plugin_Admin.php:926
#: Generic_Plugin_Admin.php:941
msgid "%1$s could not be written, please edit config and add:%2$s before %3$s."
msgstr ""
#: Generic_Plugin_Admin.php:934
#: Generic_Plugin_Admin.php:949
msgid "Pull Zone could not be automatically created."
msgstr ""
#: Generic_Plugin_Admin.php:938
#: Generic_Plugin_Admin.php:953
msgid "Plugin configuration successfully updated."
msgstr ""
#: Generic_Plugin_Admin.php:939
#: Generic_Plugin_Admin.php:954
msgid "All caches successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:940
#: Generic_Plugin_Admin.php:955
msgid "Memcached cache(s) successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:941
#: Generic_Plugin_Admin.php:956
msgid "Opcode cache(s) successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:942
#: Generic_Plugin_Admin.php:957
msgid "Disk cache(s) successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:943
#: Generic_Plugin_Admin.php:958
msgid "Page cache successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:944
#: Generic_Plugin_Admin.php:959
msgid "Database cache successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:945
#: Generic_Plugin_Admin.php:960
msgid "Object cache successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:946
#: Generic_Plugin_Admin.php:961
msgid "Fragment cache successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:947
#: Generic_Plugin_Admin.php:962
msgid "Minify cache successfully emptied."
msgstr ""
#: Generic_Plugin_Admin.php:948
#: Generic_Plugin_Admin.php:963
msgid "Media Query string has been successfully updated."
msgstr ""
#: Generic_Plugin_Admin.php:949
#: Generic_Plugin_Admin.php:964
msgid "Varnish servers successfully purged."
msgstr ""
#. translators: 1 HTML acronym for CDN (content delivery network).
#: Generic_Plugin_Admin.php:952
#: Generic_Plugin_Admin.php:967
msgid "%1$s was successfully purged."
msgstr ""
#: Generic_Plugin_Admin.php:958
#: Generic_Plugin_Admin.php:973
msgid "The support request has been successfully sent."
msgstr ""
#: Generic_Plugin_Admin.php:959
#: Generic_Plugin_Admin.php:974
msgid "Settings successfully imported."
msgstr ""
#: Generic_Plugin_Admin.php:960
#: Generic_Plugin_Admin.php:975
msgid "Settings successfully restored."
msgstr ""
#: Generic_Plugin_Admin.php:961
#: Generic_Plugin_Admin.php:976
msgid "Preview mode was successfully enabled"
msgstr ""
#: Generic_Plugin_Admin.php:962
#: Generic_Plugin_Admin.php:977
msgid "Preview mode was successfully disabled"
msgstr ""
#: Generic_Plugin_Admin.php:963
#: Generic_Plugin_Admin.php:978
msgid "Preview settings successfully deployed. Preview mode remains enabled until it's disabled. Continue testing new settings or disable preview mode if done."
msgstr ""
#: Generic_Plugin_Admin.php:964
#: Generic_Plugin_Admin.php:979
msgid "Attachment successfully purged."
msgstr ""
#: Generic_Plugin_Admin.php:965
#: Generic_Plugin_Admin.php:980
msgid "Post successfully purged."
msgstr ""
#: Generic_Plugin_Admin.php:966
#: Generic_Plugin_Admin.php:981
msgid "New relic settings have been updated."
msgstr ""
#: Generic_Plugin_Admin.php:967
#: Generic_Plugin_Admin.php:982
msgid "The add-in has been removed."
msgstr ""
#: Generic_Plugin_Admin.php:968
#: Generic_Plugin_Admin.php:983
msgid "Edge mode has been enabled."
msgstr ""
#: Generic_Plugin_Admin.php:969
#: Generic_Plugin_Admin.php:984
msgid "Edge mode has been disabled."
msgstr ""
#: Generic_Plugin_Admin.php:970
#: Generic_Plugin_Admin.php:985
msgid "Pull Zone was automatically created."
msgstr ""
#: Generic_Plugin_Admin.php:1020
#: Generic_Plugin_Admin.php:1035
msgid "Required files and directories have been automatically created"
msgstr ""
#: Generic_Plugin_Admin.php:1047
#: Generic_Plugin_Admin.php:1062
msgid "W3 Total Cache Error:"
msgstr ""
#: Generic_Plugin_Admin.php:1048
#: Generic_Plugin_Admin.php:1063
msgid "Files and directories could not be automatically created to complete the installation."
msgstr ""
#: Generic_Plugin_Admin.php:1051
#: Generic_Plugin_Admin.php:1066
#: Util_Activation.php:240
msgid "Please execute commands manually"
msgstr ""
#: Generic_Plugin_Admin.php:1052
#: Generic_Plugin_Admin.php:1067
#: Util_Activation.php:244
msgid "View required changes"
msgstr ""
#: Generic_Plugin_Admin.php:1055
#: Generic_Plugin_Admin.php:1070
msgid "or use FTP form to allow "
msgstr ""
#: Generic_Plugin_Admin.php:1057
#: Generic_Plugin_Admin.php:1072
msgid "make it automatically."
msgstr ""
@ -6764,7 +6764,7 @@ msgstr ""
#: inc/options/browsercache.php:509
#: inc/options/pgcache.php:258
#: inc/options/pgcache.php:794
#: inc/options/pgcache.php:795
msgid "Extensible Markup Language"
msgstr ""
@ -6784,7 +6784,7 @@ msgstr ""
#: inc/options/cdn.php:26
#: inc/options/common/header.php:193
#: inc/options/common/header.php:268
#: inc/options/pgcache.php:813
#: inc/options/pgcache.php:814
msgid "Note(s)"
msgstr ""
@ -6928,8 +6928,8 @@ msgstr ""
#: inc/options/dbcache.php:109
#: inc/options/install.php:83
#: inc/options/install.php:255
#: inc/options/pgcache.php:671
#: inc/options/pgcache.php:742
#: inc/options/pgcache.php:672
#: inc/options/pgcache.php:743
#: PageSpeed_Instructions.php:70
#: PageSpeed_Instructions.php:87
#: PageSpeed_Instructions.php:359
@ -8451,7 +8451,7 @@ msgstr ""
#: inc/options/minify.php:1051
#: inc/options/pgcache.php:592
#: inc/options/pgcache.php:594
#: inc/options/pgcache.php:858
#: inc/options/pgcache.php:859
msgid "Time to Live"
msgstr ""
@ -8624,7 +8624,7 @@ msgstr ""
#: inc/options/parts/memcached.php:23
#: inc/options/parts/memcached_extension.php:25
msgid "Multiple servers may be used and seperated by a comma; e.g. 192.168.1.100:11211, domain.com:22122"
msgid "Multiple servers may be used and seperated by a comma; e.g. 127.0.0.1:11211, domain.com:11211"
msgstr ""
#: inc/options/parts/memcached.php:27
@ -8706,7 +8706,7 @@ msgstr ""
#: inc/options/parts/redis.php:30
#: inc/options/parts/redis_extension.php:32
msgid "Multiple servers may be used and seperated by a comma; e.g. 192.168.1.100:11211, domain.com:22122. To use TLS, prefix server with tls://"
msgid "Multiple servers may be used and seperated by a comma; e.g. 127.0.0.1:6379, domain.com:6379. To use TLS, prefix server with tls://"
msgstr ""
#: inc/options/parts/redis.php:38
@ -8934,64 +8934,64 @@ msgid "Significantly reduce the default %1$sTTL%2$s for comment cookies to reduc
msgstr ""
#. translators: 1 opening HTML acronym tag, 2 closing HTML acronym tag.
#: inc/options/pgcache.php:618
#: inc/options/pgcache.php:619
msgid "Always cache %1$sURL%2$ss that use these query string name-value pairs. The value part is not required. But if used, separate name-value pairs with an equals sign (i.e., name=value). Each pair should be on their own line."
msgstr ""
#: inc/options/pgcache.php:641
#: inc/options/pgcache.php:642
msgid "Never send cache pages for these user agents."
msgstr ""
#: inc/options/pgcache.php:650
#: inc/options/pgcache.php:651
msgid "Never cache pages that use the specified cookies."
msgstr ""
#. translators: 2 opening HTML acronym tag, 3 closing HTML acronym tag, 4 closing HTML acronym tag.
#: inc/options/pgcache.php:666
#: inc/options/pgcache.php:667
msgid "Always ignore the specified pages / directories. Supports regular expressions (See %1$s%2$sFAQ%3$s%4$s)"
msgstr ""
#: inc/options/pgcache.php:694
#: inc/options/pgcache.php:695
msgid "Always ignore all pages filed under the specified category slugs."
msgstr ""
#: inc/options/pgcache.php:703
#: inc/options/pgcache.php:704
msgid "Always ignore all pages filed under the specified tag slugs."
msgstr ""
#: inc/options/pgcache.php:712
#: inc/options/pgcache.php:713
msgid "Always ignore all pages filed under the specified author usernames."
msgstr ""
#: inc/options/pgcache.php:721
#: inc/options/pgcache.php:722
msgid "Always ignore all pages filed under the specified custom fields. Separate name-value pairs with an equals sign (i.e., name=value)."
msgstr ""
#. translators: 3 closing HTML acronym tag, 4 closing HTML acronym tag.
#: inc/options/pgcache.php:737
#: inc/options/pgcache.php:738
msgid "Cache the specified pages / directories even if listed in the \"never cache the following pages\" field. Supports regular expression (See %1$s%2$sFAQ%3$s%4$s)"
msgstr ""
#: inc/options/pgcache.php:767
#: inc/options/pgcache.php:768
msgid "Cache the specified pages even if they don't have trailing slash."
msgstr ""
#: inc/options/pgcache.php:777
#: inc/options/pgcache.php:778
msgid "Specify additional page headers to cache."
msgstr ""
#. translators: 1 opening HTML acronym tag, 2 closing HTML acronym tag.
#: inc/options/pgcache.php:790
#: inc/options/pgcache.php:791
msgid "Return correct Content-Type header for %1$sXML%2$s files (e.g., feeds and sitemaps). Slows down cache engine."
msgstr ""
#. translators: 5 opening HTML a tag to W3TC BrowserCache admin page, 6 closing HTML a tag.
#: inc/options/pgcache.php:825
#: inc/options/pgcache.php:826
msgid "Enable %1$sHTTP%2$s compression in the \"%3$sHTML%4$s\" section on %5$sBrowser Cache</a> Settings tab."
msgstr ""
#. translators: 5 opening HTML a tag to W3TC BrowserCache admin page, 6 closing HTML a tag.
#: inc/options/pgcache.php:854
#: inc/options/pgcache.php:855
msgid "The %1$sTTL%2$s of page cache files is set via the \"Expires header lifetime\" field in the \"%3$sHTML%4$s\" section on %5$sBrowser Cache%6$s Settings tab."
msgstr ""
@ -9254,9 +9254,9 @@ msgstr ""
msgid "Upgrade"
msgstr ""
#. translators: 1 HTML input button for renewing licence.
#. translators: 1 HTML input button for renewing license.
#: Licensing_Plugin_Admin.php:169
msgid "It looks like your W3 Total Cache Pro License has expired. %1$s to continue using the Pro Features"
msgid "It looks like your W3 Total Cache Pro license has expired. %1$s to continue using the Pro features"
msgstr ""
#: Licensing_Plugin_Admin.php:175
@ -9594,7 +9594,7 @@ msgstr ""
msgid "I Understand the Risks"
msgstr ""
#: Minify_Plugin.php:317
#: Minify_Plugin.php:321
msgid "Minified using %s%s"
msgstr ""
@ -9602,21 +9602,21 @@ msgstr ""
msgid "Recently an error occurred while creating the CSS / JS minify cache: %s. %s"
msgstr ""
#: Minify_Plugin_Admin.php:145
#: Minify_Plugin_Admin.php:148
msgid "Minify: %s."
msgstr ""
#: Minify_Plugin_Admin.php:162
#: ObjectCache_Plugin_Admin.php:54
#: Minify_Plugin_Admin.php:165
#: ObjectCache_Plugin_Admin.php:60
msgid "The setting change(s) made either invalidate the cached data or modify the behavior of the site. %s now to provide a consistent user experience."
msgstr ""
#: Minify_Plugin_Admin.php:165
#: Minify_Plugin_Admin.php:168
msgid "Empty the minify cache"
msgstr ""
#: Minify_Plugin_Admin.php:189
#: Minify_Plugin_Admin.php:197
#: Minify_Plugin_Admin.php:192
#: Minify_Plugin_Admin.php:200
msgid "Minification"
msgstr ""
@ -9662,11 +9662,11 @@ msgstr ""
msgid "[W3TC] Object Cache file GC (every %d seconds)"
msgstr ""
#: ObjectCache_Plugin_Admin.php:32
#: ObjectCache_Plugin_Admin.php:38
msgid "Object Cache: %s."
msgstr ""
#: ObjectCache_Plugin_Admin.php:57
#: ObjectCache_Plugin_Admin.php:63
msgid "Empty the object cache"
msgstr ""
@ -10814,7 +10814,7 @@ msgstr ""
msgid "Page Cache: Current Page"
msgstr ""
#: PgCache_Plugin_Admin.php:290
#: PgCache_Plugin_Admin.php:293
msgid "Page Cache: %s."
msgstr ""
@ -12043,7 +12043,7 @@ msgid "FTP credentials don't allow to delete "
msgstr ""
#. translators: 1 class name, 2 file name.
#: w3-total-cache-api.php:180
#: w3-total-cache-api.php:188
msgid "Attempt to create object of class %1$s has been made, but file %2$s doesnt exists"
msgstr ""

View File

@ -445,12 +445,12 @@ class soap_transport_http extends nusoap_base {
* @param string $data message data
* @param integer $timeout set connection timeout in seconds
* @param integer $response_timeout set response timeout in seconds
* @param array $cookies cookies to send
* @param array $cookies cookies to send (6/12/2023 Made not required to prevent PHP error/warning for required following optional)
* @return string data
* @access public
* @deprecated
*/
function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies=array()) {
return $this->send($data, $timeout, $response_timeout, $cookies);
}

View File

@ -2598,12 +2598,12 @@ class soap_transport_http extends nusoap_base {
* @param string $data message data
* @param integer $timeout set connection timeout in seconds
* @param integer $response_timeout set response timeout in seconds
* @param array $cookies cookies to send
* @param array $cookies cookies to send (6/12/2023 Made not required to prevent PHP error/warning for required following optional)
* @return string data
* @access public
* @deprecated
*/
function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) {
function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies=array()) {
return $this->send($data, $timeout, $response_timeout, $cookies);
}

View File

@ -1367,7 +1367,7 @@ class CFRuntime
if (strpos($headers['_info']['url'], 'monitoring.') !== false)
{
// CloudWatchWatch incorrectly does nothing when they say deflate.
continue;
break; //(6/12/2023 Changed from continue to break to prevent PHP error/warning for required following optional)
}
else
{
@ -1387,7 +1387,7 @@ class CFRuntime
if (strpos($headers['_info']['url'], 'monitoring.') !== false)
{
// CloudWatchWatch incorrectly does nothing when they say br.
continue;
break; //(6/12/2023 Changed from continue to break to prevent PHP error/warning for required following optional)
}
else
{

View File

@ -82,12 +82,12 @@ class CFSimpleXML extends SimpleXMLIterator
*
* @param string $data (Required) A well-formed XML string or the path or URL to an XML document if $data_is_url is <code>true</code>.
* @param integer $options (Optional) Used to specify additional LibXML parameters. The default value is <code>0</code>.
* @param boolean $data_is_url (Optional) Specify a value of <code>true</code> to specify that data is a path or URL to an XML document instead of string data. The default value is <code>false</code>.
* @param string $ns (Optional) The XML namespace to return values for.
* @param boolean $data_is_url (Optional) Specify a value of <code>true</code> to specify that data is a path or URL to an XML document instead of string data. The default value is <code>false</code>. (6/12/2023 Made not required to prevent PHP error/warning for required following optional)
* @param string $ns (Optional) The XML namespace to return values for. (6/12/2023 Made not required to prevent PHP error/warning for required following optional)
* @param boolean $is_prefix (Optional) (No description provided by PHP.net.)
* @return CFSimpleXML Creates a new <CFSimpleXML> element.
*/
public static function init($data, $options = 0, $data_is_url, $ns, $is_prefix = false)
public static function init($data, $options = 0, $data_is_url=false, $ns='', $is_prefix = false)
{
if (version_compare(PHP_VERSION, '5.3.0', '<'))
{

View File

@ -3,7 +3,7 @@ Contributors: boldgrid, fredericktownes, maxicusc, gidomanders, bwmarkle, harryj
Tags: seo, cache, CDN, pagespeed, caching, performance, compression, optimize, cloudflare, nginx, apache, varnish, redis, aws, amazon web services, s3, cloudfront, azure
Requires at least: 5.3
Tested up to: 6.2
Stable tag: 2.3.2
Stable tag: 2.3.3
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
@ -285,6 +285,13 @@ Please reach out to all of these people and support their projects if you're so
== Changelog ==
= 2.3.3 =
* Fix: Fragment Cache: Fatal error when displaying registered groups
* Fix: PHP 8 deprecation warnings in the SNS Message Bus and NuSOAP libraries
* Fix: Broken nonce for renewal form
* Fix: Page Cache: Moved hardcoded query string exemptions to the settings page
* Update: Redis and Memcached host/IP/domain configuration examples
= 2.3.2 =
* Fix: Correct interpolation of a symlinked cache directory
* Fix: Memcached test using SASL authentication

View File

@ -4,4 +4,4 @@
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitec9f036f36a966a3253a9d48a939695c::getLoader();
return ComposerAutoloaderInit0ee4571b977b8bb5c07fd4829a0db478::getLoader();

View File

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitec9f036f36a966a3253a9d48a939695c
class ComposerAutoloaderInit0ee4571b977b8bb5c07fd4829a0db478
{
private static $loader;
@ -22,15 +22,15 @@ class ComposerAutoloaderInitec9f036f36a966a3253a9d48a939695c
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitec9f036f36a966a3253a9d48a939695c', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInit0ee4571b977b8bb5c07fd4829a0db478', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitec9f036f36a966a3253a9d48a939695c', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInit0ee4571b977b8bb5c07fd4829a0db478', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitec9f036f36a966a3253a9d48a939695c::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInit0ee4571b977b8bb5c07fd4829a0db478::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
@ -51,19 +51,19 @@ class ComposerAutoloaderInitec9f036f36a966a3253a9d48a939695c
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInitec9f036f36a966a3253a9d48a939695c::$files;
$includeFiles = Composer\Autoload\ComposerStaticInit0ee4571b977b8bb5c07fd4829a0db478::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequireec9f036f36a966a3253a9d48a939695c($fileIdentifier, $file);
composerRequire0ee4571b977b8bb5c07fd4829a0db478($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequireec9f036f36a966a3253a9d48a939695c($fileIdentifier, $file)
function composerRequire0ee4571b977b8bb5c07fd4829a0db478($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;

View File

@ -4,7 +4,7 @@
namespace Composer\Autoload;
class ComposerStaticInitec9f036f36a966a3253a9d48a939695c
class ComposerStaticInit0ee4571b977b8bb5c07fd4829a0db478
{
public static $files = array (
'7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php',
@ -986,9 +986,9 @@ class ComposerStaticInitec9f036f36a966a3253a9d48a939695c
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitec9f036f36a966a3253a9d48a939695c::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitec9f036f36a966a3253a9d48a939695c::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitec9f036f36a966a3253a9d48a939695c::$classMap;
$loader->prefixLengthsPsr4 = ComposerStaticInit0ee4571b977b8bb5c07fd4829a0db478::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit0ee4571b977b8bb5c07fd4829a0db478::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit0ee4571b977b8bb5c07fd4829a0db478::$classMap;
}, null, ClassLoader::class);
}

View File

@ -178,7 +178,7 @@
"dev-master": "6.5-dev"
}
},
"installation-source": "dist",
"installation-source": "source",
"autoload": {
"files": [
"src/functions_include.php"
@ -256,17 +256,17 @@
},
{
"name": "guzzlehttp/promises",
"version": "1.5.2",
"version_normalized": "1.5.2.0",
"version": "1.5.3",
"version_normalized": "1.5.3.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
"reference": "b94b2807d85443f9719887892882d0329d1e2598"
"reference": "67ab6e18aaa14d753cc148911d273f6e6cb6721e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/promises/zipball/b94b2807d85443f9719887892882d0329d1e2598",
"reference": "b94b2807d85443f9719887892882d0329d1e2598",
"url": "https://api.github.com/repos/guzzle/promises/zipball/67ab6e18aaa14d753cc148911d273f6e6cb6721e",
"reference": "67ab6e18aaa14d753cc148911d273f6e6cb6721e",
"shasum": ""
},
"require": {
@ -275,13 +275,8 @@
"require-dev": {
"symfony/phpunit-bridge": "^4.4 || ^5.1"
},
"time": "2022-08-28T14:55:35+00:00",
"time": "2023-05-21T12:31:43+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.5-dev"
}
},
"installation-source": "dist",
"autoload": {
"files": [
@ -368,7 +363,7 @@
},
"time": "2023-04-17T16:00:37+00:00",
"type": "library",
"installation-source": "dist",
"installation-source": "source",
"autoload": {
"files": [
"src/functions_include.php"

View File

@ -0,0 +1,11 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending for every file
# Indent with 4 spaces
[php]
end_of_line = lf
indent_style = space
indent_size = 4

View File

@ -0,0 +1,11 @@
.editorconfig export-ignore
.gitattributes export-ignore
/.github/ export-ignore
.gitignore export-ignore
/build/ export-ignore
/docs/ export-ignore
/Makefile export-ignore
/phpstan-baseline.neon export-ignore
/phpstan.neon.dist export-ignore
/phpunit.xml.dist export-ignore
/tests/ export-ignore

View File

@ -0,0 +1,3 @@
# Contributing
Please see our [contributing guide](http://docs.guzzlephp.org/en/latest/overview.html#contributing).

View File

@ -0,0 +1 @@
Please consider using one of the issue templates (bug report, feature request).

View File

@ -0,0 +1,18 @@
---
name: 🐛 Bug Report
about: Report errors and problems
---
**Guzzle version(s) affected**: x.y.z
**Description**
<!-- A clear and concise description of the problem. -->
**How to reproduce**
<!-- Code and/or config needed to reproduce the problem. -->
**Possible Solution**
<!--- Optional: only if you have suggestions on a fix/reason for the bug -->
**Additional context**
<!-- Optional: any other context about the problem: log messages, screenshots, etc. -->

View File

@ -0,0 +1,14 @@
---
name: 🚀 Feature Request
about: RFC and ideas for new features and improvements
---
**Description**
<!-- A clear and concise description of the new feature. -->
**Example**
<!-- A simple example of the new feature in action (include PHP code, YAML config, etc.)
If the new feature changes an existing feature, include a simple before/after comparison. -->
**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->

View File

@ -0,0 +1,10 @@
---
name: ⛔ Security Issue
about: See the description to report security-related issues
---
⚠ PLEASE DON'T DISCLOSE SECURITY-RELATED ISSUES PUBLICLY, SEE BELOW.
If you have found a security issue in Guzzle, please send the details to
security [at] guzzlephp.org and don't disclose it publicly until we can provide a
fix for it.

View File

@ -0,0 +1,10 @@
---
name: ⛔ Support Question
about: See https://github.com/guzzle/guzzle/blob/master/.github/SUPPORT.md for questions about using Guzzle and its components
---
We use GitHub issues only to discuss about Guzzle bugs and new features.
For this kind of questions about using Guzzle,
please use any of the support alternatives shown in https://github.com/guzzle/guzzle/blob/master/.github/SUPPORT.md
Thanks!

View File

@ -0,0 +1,18 @@
# Support
If you're looking for support for Guzzle, here are a few options:
- [Documentation](http://guzzlephp.org/)
- [Gitter](https://gitter.im/guzzle/guzzle)
- [#guzzle](https://php-http.slack.com/messages/CE6UAAKL4/) channel in [PHP-HTTP](http://php-http.org) Slack team
Guzzle is a relatively old project, so chances are you will find
much about them on Google or Stack Overflow:
- [guzzle](https://stackoverflow.com/questions/tagged/guzzle) tag on Stack Overflow (recommended)
- [guzzlehttp](https://stackoverflow.com/questions/tagged/guzzlehttp) tag on Stack Overflow
- [guzzle6](https://stackoverflow.com/questions/tagged/guzzle6) tag on Stack Overflow
You can also browse the issue tracker for support requests,
but we encourage everyone to use the channels above instead.

View File

@ -0,0 +1,37 @@
#!/bin/sh -l
#
# This file is a hack to suppress warnings from Roave BC check
#
composer install
# Capture output to variable AND print it
exec 4711>&1
OUTPUT=$(/composer/vendor/bin/roave-backward-compatibility-check 2>&1 | tee /dev/fd/4711)
# Remove rows we want to suppress
OUTPUT=`echo "$OUTPUT" | sed '/GuzzleHttp\\\ClientInterface::VERSION/'d`
OUTPUT=`echo "$OUTPUT" | sed '/Roave\\\BetterReflection\\\Reflection\\\ReflectionClass "Psr\\\Log\\\LogLevel" could not be found in the located source/'d`
# Number of rows we found with "[BC]" in them
BC_BREAKS=`echo "$OUTPUT" | grep -o '\[BC\]' | wc -l | awk '{ print $1 }'`
# The last row of the output is "X backwards-incompatible changes detected". Find X.
STATED_BREAKS=`echo "$OUTPUT" | tail -n 1 | awk -F' ' '{ print $1 }'`
# If
# We found "[BC]" in the command output after we removed suppressed lines
# OR
# We have suppressed X number of BC breaks. If $STATED_BREAKS is larger than X
# THEN
# exit 1
if [ $BC_BREAKS -gt 0 ] || [ $STATED_BREAKS -gt 2 ]; then
echo "EXIT 1"
exit 1
fi
# No BC breaks found
echo "EXIT 0"
exit 0

View File

@ -0,0 +1,21 @@
name: Checks
on:
push:
branches:
- master
pull_request:
jobs:
roave-bc-check:
name: Roave BC Check
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Roave BC Check
uses: docker://nyholm/roave-bc-check-ga
with:
entrypoint: ./.github/workflows/bc.entrypoint

View File

@ -0,0 +1,70 @@
name: CI
on:
push:
branches:
- master
pull_request:
jobs:
build-lowest:
name: Build lowest
runs-on: ubuntu-latest
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '5.5'
coverage: none
extensions: mbstring, intl
- name: Set up Node
uses: actions/setup-node@v1
with:
node-version: '14.x'
- name: Setup Problem Matchers for PHPUnit
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Checkout code
uses: actions/checkout@v2
- name: Download dependencies
run: composer update --no-interaction --no-progress --prefer-stable --prefer-lowest
- name: Run tests
run: make test
build:
name: Build
runs-on: ubuntu-latest
strategy:
max-parallel: 10
matrix:
php: ['5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4']
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
extensions: mbstring, intl
- name: Set up Node
uses: actions/setup-node@v1
with:
node-version: '14.x'
- name: Setup Problem Matchers for PHPUnit
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Checkout code
uses: actions/checkout@v2
- name: Download dependencies
run: composer update --no-interaction --no-progress
- name: Run tests
run: make test

View File

@ -0,0 +1,78 @@
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " start-server to start the test server"
@echo " stop-server to stop the test server"
@echo " test to perform unit tests. Provide TEST to perform a specific test."
@echo " coverage to perform unit tests with code coverage. Provide TEST to perform a specific test."
@echo " coverage-show to show the code coverage report"
@echo " clean to remove build artifacts"
@echo " docs to build the Sphinx docs"
@echo " docs-show to view the Sphinx docs"
@echo " tag to modify the version, update changelog, and chag tag"
@echo " package to build the phar and zip files"
@echo " static to run phpstan and php-cs-fixer on the codebase"
@echo " static-phpstan to run phpstan on the codebase"
@echo " static-phpstan-update-baseline to regenerate the phpstan baseline file"
@echo " static-codestyle-fix to run php-cs-fixer on the codebase, writing the changes"
@echo " static-codestyle-check to run php-cs-fixer on the codebase"
start-server: stop-server
node tests/server.js &> /dev/null &
stop-server:
@PID=$(shell ps axo pid,command \
| grep 'tests/server.js' \
| grep -v grep \
| cut -f 1 -d " "\
) && [ -n "$$PID" ] && kill $$PID || true
test: start-server
vendor/bin/phpunit
$(MAKE) stop-server
coverage: start-server
vendor/bin/phpunit --coverage-html=build/artifacts/coverage
$(MAKE) stop-server
coverage-show: view-coverage
view-coverage:
open build/artifacts/coverage/index.html
clean:
rm -rf artifacts/*
docs:
cd docs && make html && cd ..
docs-show:
open docs/_build/html/index.html
tag:
$(if $(TAG),,$(error TAG is not defined. Pass via "make tag TAG=4.2.1"))
@echo Tagging $(TAG)
chag update $(TAG)
sed -i '' -e "s/VERSION = '.*'/VERSION = '$(TAG)'/" src/ClientInterface.php
php -l src/ClientInterface.php
git add -A
git commit -m '$(TAG) release'
chag tag
package:
php build/packager.php
static: static-phpstan static-codestyle-check
static-phpstan:
docker run --rm -it -e REQUIRE_DEV=true -v ${PWD}:/app -w /app oskarstark/phpstan-ga:0.12.28 analyze $(PHPSTAN_PARAMS)
static-phpstan-update-baseline:
$(MAKE) static-phpstan PHPSTAN_PARAMS="--generate-baseline"
static-codestyle-fix:
docker run --rm -it -v ${PWD}:/app -w /app oskarstark/php-cs-fixer-ga:2.16.3.1 --diff-format udiff $(CS_PARAMS)
static-codestyle-check:
$(MAKE) static-codestyle-fix CS_PARAMS="--dry-run"
.PHONY: docs burgomaster coverage-show view-coverage

View File

@ -0,0 +1,385 @@
<?php
/**
* Packages the zip and phar file using a staging directory.
*
* @license MIT, Michael Dowling https://github.com/mtdowling
* @license https://github.com/mtdowling/Burgomaster/LICENSE
*/
class Burgomaster
{
/** @var string Base staging directory of the project */
public $stageDir;
/** @var string Root directory of the project */
public $projectRoot;
/** @var array stack of sections */
private $sections = array();
/**
* @param string $stageDir Staging base directory where your packaging
* takes place. This folder will be created for
* you if it does not exist. If it exists, it
* will be deleted and recreated to start fresh.
* @param string $projectRoot Root directory of the project.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function __construct($stageDir, $projectRoot = null)
{
$this->startSection('setting_up');
$this->stageDir = $stageDir;
$this->projectRoot = $projectRoot;
if (!$this->stageDir || $this->stageDir == '/') {
throw new \InvalidArgumentException('Invalid base directory');
}
if (is_dir($this->stageDir)) {
$this->debug("Removing existing directory: $this->stageDir");
echo $this->exec("rm -rf $this->stageDir");
}
$this->debug("Creating staging directory: $this->stageDir");
if (!mkdir($this->stageDir, 0777, true)) {
throw new \RuntimeException("Could not create {$this->stageDir}");
}
$this->stageDir = realpath($this->stageDir);
$this->debug("Creating staging directory at: {$this->stageDir}");
if (!is_dir($this->projectRoot)) {
throw new \InvalidArgumentException(
"Project root not found: $this->projectRoot"
);
}
$this->endSection();
$this->startSection('staging');
chdir($this->projectRoot);
}
/**
* Cleanup if the last section was not already closed.
*/
public function __destruct()
{
if ($this->sections) {
$this->endSection();
}
}
/**
* Call this method when starting a specific section of the packager.
*
* This makes the debug messages used in your script more meaningful and
* adds context when things go wrong. Be sure to call endSection() when
* you have finished a section of your packaging script.
*
* @param string $section Part of the packager that is running
*/
public function startSection($section)
{
$this->sections[] = $section;
$this->debug('Starting');
}
/**
* Call this method when leaving the last pushed section of the packager.
*/
public function endSection()
{
if ($this->sections) {
$this->debug('Completed');
array_pop($this->sections);
}
}
/**
* Prints a debug message to STDERR bound to the current section.
*
* @param string $message Message to echo to STDERR
*/
public function debug($message)
{
$prefix = date('c') . ': ';
if ($this->sections) {
$prefix .= '[' . end($this->sections) . '] ';
}
fwrite(STDERR, $prefix . $message . "\n");
}
/**
* Copies a file and creates the destination directory if needed.
*
* @param string $from File to copy
* @param string $to Destination to copy the file to, relative to the
* base staging directory.
* @throws \InvalidArgumentException if the file cannot be found
* @throws \RuntimeException if the directory cannot be created.
* @throws \RuntimeException if the file cannot be copied.
*/
public function deepCopy($from, $to)
{
if (!is_file($from)) {
throw new \InvalidArgumentException("File not found: {$from}");
}
$to = str_replace('//', '/', $this->stageDir . '/' . $to);
$dir = dirname($to);
if (!is_dir($dir)) {
if (!mkdir($dir, 0777, true)) {
throw new \RuntimeException("Unable to create directory: $dir");
}
}
if (!copy($from, $to)) {
throw new \RuntimeException("Unable to copy $from to $to");
}
}
/**
* Recursively copy one folder to another.
*
* Any LICENSE file is automatically copied.
*
* @param string $sourceDir Source directory to copy from
* @param string $destDir Directory to copy the files to that is relative
* to the the stage base directory.
* @param array $extensions File extensions to copy from the $sourceDir.
* Defaults to "php" files only (e.g., ['php']).
* @throws \InvalidArgumentException if the source directory is invalid.
*/
public function recursiveCopy(
$sourceDir,
$destDir,
$extensions = array('php')
) {
if (!realpath($sourceDir)) {
throw new \InvalidArgumentException("$sourceDir not found");
}
if (!$extensions) {
throw new \InvalidArgumentException('$extensions is empty!');
}
$sourceDir = realpath($sourceDir);
$exts = array_fill_keys($extensions, true);
$iter = new \RecursiveDirectoryIterator($sourceDir);
$iter = new \RecursiveIteratorIterator($iter);
$total = 0;
$this->startSection('copy');
$this->debug("Starting to copy files from $sourceDir");
foreach ($iter as $file) {
if (isset($exts[$file->getExtension()])
|| $file->getBaseName() == 'LICENSE'
) {
// Remove the source directory from the destination path
$toPath = str_replace($sourceDir, '', (string) $file);
$toPath = $destDir . '/' . $toPath;
$toPath = str_replace('//', '/', $toPath);
$this->deepCopy((string) $file, $toPath);
$total++;
}
}
$this->debug("Copied $total files from $sourceDir");
$this->endSection();
}
/**
* Execute a command and throw an exception if the return code is not 0.
*
* @param string $command Command to execute
*
* @return string Returns the output of the command as a string
* @throws \RuntimeException on error.
*/
public function exec($command)
{
$this->debug("Executing: $command");
$output = $returnValue = null;
exec($command, $output, $returnValue);
if ($returnValue != 0) {
throw new \RuntimeException('Error executing command: '
. $command . ' : ' . implode("\n", $output));
}
return implode("\n", $output);
}
/**
* Creates a class-map autoloader to the staging directory in a file
* named autoloader.php
*
* @param array $files Files to explicitly require in the autoloader. This
* is similar to Composer's "files" "autoload" section.
* @param string $filename Name of the autoloader file.
* @throws \RuntimeException if the file cannot be written
*/
public function createAutoloader($files = array(), $filename = 'autoloader.php')
{
$sourceDir = realpath($this->stageDir);
$iter = new \RecursiveDirectoryIterator($sourceDir);
$iter = new \RecursiveIteratorIterator($iter);
$this->startSection('autoloader');
$this->debug('Creating classmap autoloader');
$this->debug("Collecting valid PHP files from {$this->stageDir}");
$classMap = array();
foreach ($iter as $file) {
if ($file->getExtension() == 'php') {
$location = str_replace($this->stageDir . '/', '', (string) $file);
$className = str_replace('/', '\\', $location);
$className = substr($className, 0, -4);
// Remove "src\" or "lib\"
if (strpos($className, 'src\\') === 0
|| strpos($className, 'lib\\') === 0
) {
$className = substr($className, 4);
}
$classMap[$className] = "__DIR__ . '/$location'";
$this->debug("Found $className");
}
}
$destFile = $this->stageDir . '/' . $filename;
$this->debug("Writing autoloader to {$destFile}");
if (!($h = fopen($destFile, 'w'))) {
throw new \RuntimeException('Unable to open file for writing');
}
$this->debug('Writing classmap files');
fwrite($h, "<?php\n\n");
fwrite($h, "\$mapping = array(\n");
foreach ($classMap as $c => $f) {
fwrite($h, " '$c' => $f,\n");
}
fwrite($h, ");\n\n");
fwrite($h, <<<EOT
spl_autoload_register(function (\$class) use (\$mapping) {
if (isset(\$mapping[\$class])) {
require \$mapping[\$class];
}
}, true);
EOT
);
fwrite($h, "\n");
$this->debug('Writing automatically included files');
foreach ($files as $file) {
fwrite($h, "require __DIR__ . '/$file';\n");
}
fclose($h);
$this->endSection();
}
/**
* Creates a default stub for the phar that includeds the generated
* autoloader.
*
* This phar also registers a constant that can be used to check if you
* are running the phar. The constant is the basename of the $dest variable
* without the extension, with "_PHAR" appended, then converted to all
* caps (e.g., "/foo/guzzle.phar" gets a contant defined as GUZZLE_PHAR.
*
* @param $dest
* @param string $autoloaderFilename Name of the autoloader file.
*
* @return string
*/
private function createStub($dest, $autoloaderFilename = 'autoloader.php')
{
$this->startSection('stub');
$this->debug("Creating phar stub at $dest");
$alias = basename($dest);
$constName = str_replace('.phar', '', strtoupper($alias)) . '_PHAR';
$stub = "<?php\n";
$stub .= "define('$constName', true);\n";
$stub .= "require 'phar://$alias/{$autoloaderFilename}';\n";
$stub .= "__HALT_COMPILER();\n";
$this->endSection();
return $stub;
}
/**
* Creates a phar that automatically registers an autoloader.
*
* Call this only after your staging directory is built.
*
* @param string $dest Where to save the file. The basename of the file
* is also used as the alias name in the phar
* (e.g., /path/to/guzzle.phar => guzzle.phar).
* @param string|bool|null $stub The path to the phar stub file. Pass or
* leave null to automatically have one created for you. Pass false
* to no use a stub in the generated phar.
* @param string $autoloaderFilename Name of the autolaoder filename.
*/
public function createPhar(
$dest,
$stub = null,
$autoloaderFilename = 'autoloader.php'
) {
$this->startSection('phar');
$this->debug("Creating phar file at $dest");
$this->createDirIfNeeded(dirname($dest));
$phar = new \Phar($dest, 0, basename($dest));
$phar->buildFromDirectory($this->stageDir);
if ($stub !== false) {
if (!$stub) {
$stub = $this->createStub($dest, $autoloaderFilename);
}
$phar->setStub($stub);
}
$this->debug("Created phar at $dest");
$this->endSection();
}
/**
* Creates a zip file containing the staged files of your project.
*
* Call this only after your staging directory is built.
*
* @param string $dest Where to save the zip file
*/
public function createZip($dest)
{
$this->startSection('zip');
$this->debug("Creating a zip file at $dest");
$this->createDirIfNeeded(dirname($dest));
chdir($this->stageDir);
$this->exec("zip -r $dest ./");
$this->debug(" > Created at $dest");
chdir(__DIR__);
$this->endSection();
}
private function createDirIfNeeded($dir)
{
if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
throw new \RuntimeException("Could not create dir: $dir");
}
}
}

View File

@ -0,0 +1,27 @@
<?php
require __DIR__ . '/Burgomaster.php';
$stageDirectory = __DIR__ . '/artifacts/staging';
$projectRoot = __DIR__ . '/../';
$packager = new \Burgomaster($stageDirectory, $projectRoot);
// Copy basic files to the stage directory. Note that we have chdir'd onto
// the $projectRoot directory, so use relative paths.
foreach (['README.md', 'LICENSE'] as $file) {
$packager->deepCopy($file, $file);
}
// Copy each dependency to the staging directory. Copy *.php and *.pem files.
$packager->recursiveCopy('src', 'GuzzleHttp', ['php']);
$packager->recursiveCopy('vendor/guzzlehttp/promises/src', 'GuzzleHttp/Promise');
$packager->recursiveCopy('vendor/guzzlehttp/psr7/src', 'GuzzleHttp/Psr7');
$packager->recursiveCopy('vendor/psr/http-message/src', 'Psr/Http/Message');
$packager->createAutoloader([
'GuzzleHttp/functions_include.php',
'GuzzleHttp/Psr7/functions_include.php',
'GuzzleHttp/Promise/functions_include.php',
]);
$packager->createPhar(__DIR__ . '/artifacts/guzzle.phar');
$packager->createZip(__DIR__ . '/artifacts/guzzle.zip');

View File

@ -0,0 +1,153 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Guzzle.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Guzzle.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Guzzle"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Guzzle"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

Binary file not shown.

After

Width:  |  Height:  |  Size: 803 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 242 KiB

View File

@ -0,0 +1,68 @@
import sys, os
from sphinx.highlighting import lexers
from pygments.lexers.web import PhpLexer
lexers['php'] = PhpLexer(startinline=True, linenos=1)
lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1)
primary_domain = 'php'
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Guzzle'
copyright = u'2015, Michael Dowling'
version = '6'
html_title = "Guzzle Documentation"
html_short_title = "Guzzle 6"
exclude_patterns = ['_build']
html_static_path = ['_static']
##### Guzzle sphinx theme
import guzzle_sphinx_theme
html_translator_class = 'guzzle_sphinx_theme.HTMLTranslator'
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = 'guzzle_sphinx_theme'
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': ['logo-text.html', 'globaltoc.html', 'searchbox.html']
}
# Register the theme as an extension to generate a sitemap.xml
extensions.append("guzzle_sphinx_theme")
# Guzzle theme options (see theme.conf for more information)
html_theme_options = {
# Set the path to a special layout to include for the homepage
# "index_template": "homepage.html",
# Allow a separate homepage from the master_doc
# homepage = index
# Set the name of the project to appear in the nav menu
# "project_nav_name": "Guzzle",
# Set your Disqus short name to enable comments
# "disqus_comments_shortname": "my_disqus_comments_short_name",
# Set you GA account ID to enable tracking
# "google_analytics_account": "my_ga_account",
# Path to a touch icon
# "touch_icon": "",
# Specify a base_url used to generate sitemap.xml links. If not
# specified, then no sitemap will be built.
"base_url": "http://guzzlephp.org"
# Allow the "Table of Contents" page to be defined separately from "master_doc"
# tocpage = Contents
# Allow the project link to be overriden to a custom URL.
# projectlink = http://myproject.url
}

View File

@ -0,0 +1,193 @@
===
FAQ
===
Does Guzzle require cURL?
=========================
No. Guzzle can use any HTTP handler to send requests. This means that Guzzle
can be used with cURL, PHP's stream wrapper, sockets, and non-blocking libraries
like `React <http://reactphp.org/>`_. You just need to configure an HTTP handler
to use a different method of sending requests.
.. note::
Guzzle has historically only utilized cURL to send HTTP requests. cURL is
an amazing HTTP client (arguably the best), and Guzzle will continue to use
it by default when it is available. It is rare, but some developers don't
have cURL installed on their systems or run into version specific issues.
By allowing swappable HTTP handlers, Guzzle is now much more customizable
and able to adapt to fit the needs of more developers.
Can Guzzle send asynchronous requests?
======================================
Yes. You can use the ``requestAsync``, ``sendAsync``, ``getAsync``,
``headAsync``, ``putAsync``, ``postAsync``, ``deleteAsync``, and ``patchAsync``
methods of a client to send an asynchronous request. The client will return a
``GuzzleHttp\Promise\PromiseInterface`` object. You can chain ``then``
functions off of the promise.
.. code-block:: php
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(function ($response) {
echo 'Got a response! ' . $response->getStatusCode();
});
You can force an asynchronous response to complete using the ``wait()`` method
of the returned promise.
.. code-block:: php
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$response = $promise->wait();
How can I add custom cURL options?
==================================
cURL offers a huge number of `customizable options <http://us1.php.net/curl_setopt>`_.
While Guzzle normalizes many of these options across different handlers, there
are times when you need to set custom cURL options. This can be accomplished
by passing an associative array of cURL settings in the **curl** key of a
request.
For example, let's say you need to customize the outgoing network interface
used with a client.
.. code-block:: php
$client->request('GET', '/', [
'curl' => [
CURLOPT_INTERFACE => 'xxx.xxx.xxx.xxx'
]
]);
If you use asynchronous requests with cURL multi handler and want to tweak it,
additional options can be specified as an associative array in the
**options** key of the ``CurlMultiHandler`` constructor.
.. code-block:: php
use \GuzzleHttp\Client;
use \GuzzleHttp\HandlerStack;
use \GuzzleHttp\Handler\CurlMultiHandler;
$client = new Client(['handler' => HandlerStack::create(new CurlMultiHandler([
'options' => [
CURLMOPT_MAX_TOTAL_CONNECTIONS => 50,
CURLMOPT_MAX_HOST_CONNECTIONS => 5,
]
]))]);
How can I add custom stream context options?
============================================
You can pass custom `stream context options <http://www.php.net/manual/en/context.php>`_
using the **stream_context** key of the request option. The **stream_context**
array is an associative array where each key is a PHP transport, and each value
is an associative array of transport options.
For example, let's say you need to customize the outgoing network interface
used with a client and allow self-signed certificates.
.. code-block:: php
$client->request('GET', '/', [
'stream' => true,
'stream_context' => [
'ssl' => [
'allow_self_signed' => true
],
'socket' => [
'bindto' => 'xxx.xxx.xxx.xxx'
]
]
]);
Why am I getting an SSL verification error?
===========================================
You need to specify the path on disk to the CA bundle used by Guzzle for
verifying the peer certificate. See :ref:`verify-option`.
What is this Maximum function nesting error?
============================================
Maximum function nesting level of '100' reached, aborting
You could run into this error if you have the XDebug extension installed and
you execute a lot of requests in callbacks. This error message comes
specifically from the XDebug extension. PHP itself does not have a function
nesting limit. Change this setting in your php.ini to increase the limit::
xdebug.max_nesting_level = 1000
Why am I getting a 417 error response?
======================================
This can occur for a number of reasons, but if you are sending PUT, POST, or
PATCH requests with an ``Expect: 100-Continue`` header, a server that does not
support this header will return a 417 response. You can work around this by
setting the ``expect`` request option to ``false``:
.. code-block:: php
$client = new GuzzleHttp\Client();
// Disable the expect header on a single request
$response = $client->request('PUT', '/', ['expect' => false]);
// Disable the expect header on all client requests
$client = new GuzzleHttp\Client(['expect' => false]);
How can I track redirected requests?
====================================
You can enable tracking of redirected URIs and status codes via the
`track_redirects` option. Each redirected URI and status code will be stored in the
``X-Guzzle-Redirect-History`` and the ``X-Guzzle-Redirect-Status-History``
header respectively.
The initial request's URI and the final status code will be excluded from the results.
With this in mind you should be able to easily track a request's full redirect path.
For example, let's say you need to track redirects and provide both results
together in a single report:
.. code-block:: php
// First you configure Guzzle with redirect tracking and make a request
$client = new Client([
RequestOptions::ALLOW_REDIRECTS => [
'max' => 10, // allow at most 10 redirects.
'strict' => true, // use "strict" RFC compliant redirects.
'referer' => true, // add a Referer header
'track_redirects' => true,
],
]);
$initialRequest = '/redirect/3'; // Store the request URI for later use
$response = $client->request('GET', $initialRequest); // Make your request
// Retrieve both Redirect History headers
$redirectUriHistory = $response->getHeader('X-Guzzle-Redirect-History')[0]; // retrieve Redirect URI history
$redirectCodeHistory = $response->getHeader('X-Guzzle-Redirect-Status-History')[0]; // retrieve Redirect HTTP Status history
// Add the initial URI requested to the (beginning of) URI history
array_unshift($redirectUriHistory, $initialRequest);
// Add the final HTTP status code to the end of HTTP response history
array_push($redirectCodeHistory, $response->getStatusCode());
// (Optional) Combine the items of each array into a single result set
$fullRedirectReport = [];
foreach ($redirectUriHistory as $key => $value) {
$fullRedirectReport[$key] = ['location' => $value, 'code' => $redirectCodeHistory[$key]];
}
echo json_encode($fullRedirectReport);

View File

@ -0,0 +1,303 @@
=======================
Handlers and Middleware
=======================
Guzzle clients use a handler and middleware system to send HTTP requests.
Handlers
========
A handler function accepts a ``Psr\Http\Message\RequestInterface`` and array of
request options and returns a ``GuzzleHttp\Promise\PromiseInterface`` that is
fulfilled with a ``Psr\Http\Message\ResponseInterface`` or rejected with an
exception.
You can provide a custom handler to a client using the ``handler`` option of
a client constructor. It is important to understand that several request
options used by Guzzle require that specific middlewares wrap the handler used
by the client. You can ensure that the handler you provide to a client uses the
default middlewares by wrapping the handler in the
``GuzzleHttp\HandlerStack::create(callable $handler = null)`` static method.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
$handler = new CurlHandler();
$stack = HandlerStack::create($handler); // Wrap w/ middleware
$client = new Client(['handler' => $stack]);
The ``create`` method adds default handlers to the ``HandlerStack``. When the
``HandlerStack`` is resolved, the handlers will execute in the following order:
1. Sending request:
1. ``http_errors`` - No op when sending a request. The response status code
is checked in the response processing when returning a response promise up
the stack.
2. ``allow_redirects`` - No op when sending a request. Following redirects
occurs when a response promise is being returned up the stack.
3. ``cookies`` - Adds cookies to requests.
4. ``prepare_body`` - The body of an HTTP request will be prepared (e.g.,
add default headers like Content-Length, Content-Type, etc.).
5. <send request with handler>
2. Processing response:
1. ``prepare_body`` - no op on response processing.
2. ``cookies`` - extracts response cookies into the cookie jar.
3. ``allow_redirects`` - Follows redirects.
4. ``http_errors`` - throws exceptions when the response status code ``>=``
400.
When provided no ``$handler`` argument, ``GuzzleHttp\HandlerStack::create()``
will choose the most appropriate handler based on the extensions available on
your system.
.. important::
The handler provided to a client determines how request options are applied
and utilized for each request sent by a client. For example, if you do not
have a cookie middleware associated with a client, then setting the
``cookies`` request option will have no effect on the request.
Middleware
==========
Middleware augments the functionality of handlers by invoking them in the
process of generating responses. Middleware is implemented as a higher order
function that takes the following form.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
function my_middleware()
{
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
return $handler($request, $options);
};
};
}
Middleware functions return a function that accepts the next handler to invoke.
This returned function then returns another function that acts as a composed
handler-- it accepts a request and options, and returns a promise that is
fulfilled with a response. Your composed middleware can modify the request,
add custom request options, and modify the promise returned by the downstream
handler.
Here's an example of adding a header to each request.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
function add_header($header, $value)
{
return function (callable $handler) use ($header, $value) {
return function (
RequestInterface $request,
array $options
) use ($handler, $header, $value) {
$request = $request->withHeader($header, $value);
return $handler($request, $options);
};
};
}
Once a middleware has been created, you can add it to a client by either
wrapping the handler used by the client or by decorating a handler stack.
.. code-block:: php
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(add_header('X-Foo', 'bar'));
$client = new Client(['handler' => $stack]);
Now when you send a request, the client will use a handler composed with your
added middleware, adding a header to each request.
Here's an example of creating a middleware that modifies the response of the
downstream handler. This example adds a header to the response.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
function add_response_header($header, $value)
{
return function (callable $handler) use ($header, $value) {
return function (
RequestInterface $request,
array $options
) use ($handler, $header, $value) {
$promise = $handler($request, $options);
return $promise->then(
function (ResponseInterface $response) use ($header, $value) {
return $response->withHeader($header, $value);
}
);
};
};
}
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(add_response_header('X-Foo', 'bar'));
$client = new Client(['handler' => $stack]);
Creating a middleware that modifies a request is made much simpler using the
``GuzzleHttp\Middleware::mapRequest()`` middleware. This middleware accepts
a function that takes the request argument and returns the request to send.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::mapRequest(function (RequestInterface $request) {
return $request->withHeader('X-Foo', 'bar');
}));
$client = new Client(['handler' => $stack]);
Modifying a response is also much simpler using the
``GuzzleHttp\Middleware::mapResponse()`` middleware.
.. code-block:: php
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
use GuzzleHttp\Middleware;
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
return $response->withHeader('X-Foo', 'bar');
}));
$client = new Client(['handler' => $stack]);
HandlerStack
============
A handler stack represents a stack of middleware to apply to a base handler
function. You can push middleware to the stack to add to the top of the stack,
and unshift middleware onto the stack to add to the bottom of the stack. When
the stack is resolved, the handler is pushed onto the stack. Each value is
then popped off of the stack, wrapping the previous value popped off of the
stack.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Client;
$stack = new HandlerStack();
$stack->setHandler(\GuzzleHttp\choose_handler());
$stack->push(Middleware::mapRequest(function (RequestInterface $r) {
echo 'A';
return $r;
});
$stack->push(Middleware::mapRequest(function (RequestInterface $r) {
echo 'B';
return $r;
});
$stack->push(Middleware::mapRequest(function (RequestInterface $r) {
echo 'C';
return $r;
});
$client->request('GET', 'http://httpbin.org/');
// echoes 'ABC';
$stack->unshift(Middleware::mapRequest(function (RequestInterface $r) {
echo '0';
return $r;
});
$client = new Client(['handler' => $stack]);
$client->request('GET', 'http://httpbin.org/');
// echoes '0ABC';
You can give middleware a name, which allows you to add middleware before
other named middleware, after other named middleware, or remove middleware
by name.
.. code-block:: php
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Middleware;
// Add a middleware with a name
$stack->push(Middleware::mapRequest(function (RequestInterface $r) {
return $r->withHeader('X-Foo', 'Bar');
}, 'add_foo');
// Add a middleware before a named middleware (unshift before).
$stack->before('add_foo', Middleware::mapRequest(function (RequestInterface $r) {
return $r->withHeader('X-Baz', 'Qux');
}, 'add_baz');
// Add a middleware after a named middleware (pushed after).
$stack->after('add_baz', Middleware::mapRequest(function (RequestInterface $r) {
return $r->withHeader('X-Lorem', 'Ipsum');
});
// Remove a middleware by name
$stack->remove('add_foo');
Creating a Handler
==================
As stated earlier, a handler is a function accepts a
``Psr\Http\Message\RequestInterface`` and array of request options and returns
a ``GuzzleHttp\Promise\PromiseInterface`` that is fulfilled with a
``Psr\Http\Message\ResponseInterface`` or rejected with an exception.
A handler is responsible for applying the following :doc:`request-options`.
These request options are a subset of request options called
"transfer options".
- :ref:`cert-option`
- :ref:`connect_timeout-option`
- :ref:`debug-option`
- :ref:`delay-option`
- :ref:`decode_content-option`
- :ref:`expect-option`
- :ref:`proxy-option`
- :ref:`sink-option`
- :ref:`timeout-option`
- :ref:`ssl_key-option`
- :ref:`stream-option`
- :ref:`verify-option`

View File

@ -0,0 +1,54 @@
.. title:: Guzzle, PHP HTTP client
====================
Guzzle Documentation
====================
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
trivial to integrate with web services.
- Simple interface for building query strings, POST requests, streaming large
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
etc...
- Can send both synchronous and asynchronous requests using the same interface.
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
to utilize other PSR-7 compatible libraries with Guzzle.
- Abstracts away the underlying HTTP transport, allowing you to write
environment and transport agnostic code; i.e., no hard dependency on cURL,
PHP streams, sockets, or non-blocking event loops.
- Middleware system allows you to augment and compose client behavior.
.. code-block:: php
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type')[0];
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
User Guide
==========
.. toctree::
:maxdepth: 3
overview
quickstart
request-options
psr7
handlers-and-middleware
testing
faq

View File

@ -0,0 +1,161 @@
========
Overview
========
Requirements
============
#. PHP 5.5.0
#. To use the PHP stream handler, ``allow_url_fopen`` must be enabled in your
system's php.ini.
#. To use the cURL handler, you must have a recent version of cURL >= 7.19.4
compiled with OpenSSL and zlib.
.. note::
Guzzle no longer requires cURL in order to send HTTP requests. Guzzle will
use the PHP stream wrapper to send HTTP requests if cURL is not installed.
Alternatively, you can provide your own HTTP handler used to send requests.
Keep in mind that cURL is still required for sending concurrent requests.
.. _installation:
Installation
============
The recommended way to install Guzzle is with
`Composer <http://getcomposer.org>`_. Composer is a dependency management tool
for PHP that allows you to declare the dependencies your project needs and
installs them into your project.
.. code-block:: bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
You can add Guzzle as a dependency using the composer.phar CLI:
.. code-block:: bash
php composer.phar require guzzlehttp/guzzle:~6.0
Alternatively, you can specify Guzzle as a dependency in your project's
existing composer.json file:
.. code-block:: js
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
After installing, you need to require Composer's autoloader:
.. code-block:: php
require 'vendor/autoload.php';
You can find out more on how to install Composer, configure autoloading, and
other best-practices for defining dependencies at `getcomposer.org <http://getcomposer.org>`_.
Bleeding edge
-------------
During your development, you can keep up with the latest changes on the master
branch by setting the version requirement for Guzzle to ``~6.0@dev``.
.. code-block:: js
{
"require": {
"guzzlehttp/guzzle": "~6.0@dev"
}
}
License
=======
Licensed using the `MIT license <http://opensource.org/licenses/MIT>`_.
Copyright (c) 2015 Michael Dowling <https://github.com/mtdowling>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Contributing
============
Guidelines
----------
1. Guzzle utilizes PSR-1, PSR-2, PSR-4, and PSR-7.
2. Guzzle is meant to be lean and fast with very few dependencies. This means
that not every feature request will be accepted.
3. Guzzle has a minimum PHP version requirement of PHP 5.5. Pull requests must
not require a PHP version greater than PHP 5.5 unless the feature is only
utilized conditionally.
4. All pull requests must include unit tests to ensure the change works as
expected and to prevent regressions.
Running the tests
-----------------
In order to contribute, you'll need to checkout the source from GitHub and
install Guzzle's dependencies using Composer:
.. code-block:: bash
git clone https://github.com/guzzle/guzzle.git
cd guzzle && curl -s http://getcomposer.org/installer | php && ./composer.phar install --dev
Guzzle is unit tested with PHPUnit. Run the tests using the Makefile:
.. code-block:: bash
make test
.. note::
You'll need to install node.js v0.5.0 or newer in order to perform
integration tests on Guzzle's HTTP handlers.
Reporting a security vulnerability
==================================
We want to ensure that Guzzle is a secure HTTP client library for everyone. If
you've discovered a security vulnerability in Guzzle, we appreciate your help
in disclosing it to us in a `responsible manner <http://en.wikipedia.org/wiki/Responsible_disclosure>`_.
Publicly disclosing a vulnerability can put the entire community at risk. If
you've discovered a security concern, please email us at
security@guzzlephp.org. We'll work with you to make sure that we understand the
scope of the issue, and that we fully address your concern. We consider
correspondence sent to security@guzzlephp.org our highest priority, and work to
address any issues that arise as quickly as possible.
After a security vulnerability has been corrected, a security hotfix release will
be deployed as soon as possible.

View File

@ -0,0 +1,456 @@
================
Guzzle and PSR-7
================
Guzzle utilizes PSR-7 as the HTTP message interface. This allows Guzzle to work
with any other library that utilizes PSR-7 message interfaces.
Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTP
responses. Both requests and responses are referred to as messages.
Guzzle relies on the ``guzzlehttp/psr7`` Composer package for its message
implementation of PSR-7.
You can create a request using the ``GuzzleHttp\Psr7\Request`` class:
.. code-block:: php
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://httpbin.org/get');
// You can provide other optional constructor arguments.
$headers = ['X-Foo' => 'Bar'];
$body = 'hello!';
$request = new Request('PUT', 'http://httpbin.org/put', $headers, $body);
You can create a response using the ``GuzzleHttp\Psr7\Response`` class:
.. code-block:: php
use GuzzleHttp\Psr7\Response;
// The constructor requires no arguments.
$response = new Response();
echo $response->getStatusCode(); // 200
echo $response->getProtocolVersion(); // 1.1
// You can supply any number of optional arguments.
$status = 200;
$headers = ['X-Foo' => 'Bar'];
$body = 'hello!';
$protocol = '1.1';
$response = new Response($status, $headers, $body, $protocol);
Headers
=======
Both request and response messages contain HTTP headers.
Accessing Headers
-----------------
You can check if a request or response has a specific header using the
``hasHeader()`` method.
.. code-block:: php
use GuzzleHttp\Psr7;
$request = new Psr7\Request('GET', '/', ['X-Foo' => 'bar']);
if ($request->hasHeader('X-Foo')) {
echo 'It is there';
}
You can retrieve all the header values as an array of strings using
``getHeader()``.
.. code-block:: php
$request->getHeader('X-Foo'); // ['bar']
// Retrieving a missing header returns an empty array.
$request->getHeader('X-Bar'); // []
You can iterate over the headers of a message using the ``getHeaders()``
method.
.. code-block:: php
foreach ($request->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
Complex Headers
---------------
Some headers contain additional key value pair information. For example, Link
headers contain a link and several key value pairs:
::
<http://foo.com>; rel="thing"; type="image/jpeg"
Guzzle provides a convenience feature that can be used to parse these types of
headers:
.. code-block:: php
use GuzzleHttp\Psr7;
$request = new Psr7\Request('GET', '/', [
'Link' => '<http:/.../front.jpeg>; rel="front"; type="image/jpeg"'
]);
$parsed = Psr7\parse_header($request->getHeader('Link'));
var_export($parsed);
Will output:
.. code-block:: php
array (
0 =>
array (
0 => '<http:/.../front.jpeg>',
'rel' => 'front',
'type' => 'image/jpeg',
),
)
The result contains a hash of key value pairs. Header values that have no key
(i.e., the link) are indexed numerically while headers parts that form a key
value pair are added as a key value pair.
Body
====
Both request and response messages can contain a body.
You can retrieve the body of a message using the ``getBody()`` method:
.. code-block:: php
$response = GuzzleHttp\get('http://httpbin.org/get');
echo $response->getBody();
// JSON string: { ... }
The body used in request and response objects is a
``Psr\Http\Message\StreamInterface``. This stream is used for both
uploading data and downloading data. Guzzle will, by default, store the body of
a message in a stream that uses PHP temp streams. When the size of the body
exceeds 2 MB, the stream will automatically switch to storing data on disk
rather than in memory (protecting your application from memory exhaustion).
The easiest way to create a body for a message is using the ``stream_for``
function from the ``GuzzleHttp\Psr7`` namespace --
``GuzzleHttp\Psr7\stream_for``. This function accepts strings, resources,
callables, iterators, other streamables, and returns an instance of
``Psr\Http\Message\StreamInterface``.
The body of a request or response can be cast to a string or you can read and
write bytes off of the stream as needed.
.. code-block:: php
use GuzzleHttp\Stream\Stream;
$response = $client->request('GET', 'http://httpbin.org/get');
echo $response->getBody()->read(4);
echo $response->getBody()->read(4);
echo $response->getBody()->read(1024);
var_export($response->eof());
Requests
========
Requests are sent from a client to a server. Requests include the method to
be applied to a resource, the identifier of the resource, and the protocol
version to use.
Request Methods
---------------
When creating a request, you are expected to provide the HTTP method you wish
to perform. You can specify any method you'd like, including a custom method
that might not be part of RFC 7231 (like "MOVE").
.. code-block:: php
// Create a request using a completely custom HTTP method
$request = new \GuzzleHttp\Psr7\Request('MOVE', 'http://httpbin.org/move');
echo $request->getMethod();
// MOVE
You can create and send a request using methods on a client that map to the
HTTP method you wish to use.
:GET: ``$client->get('http://httpbin.org/get', [/** options **/])``
:POST: ``$client->post('http://httpbin.org/post', [/** options **/])``
:HEAD: ``$client->head('http://httpbin.org/get', [/** options **/])``
:PUT: ``$client->put('http://httpbin.org/put', [/** options **/])``
:DELETE: ``$client->delete('http://httpbin.org/delete', [/** options **/])``
:OPTIONS: ``$client->options('http://httpbin.org/get', [/** options **/])``
:PATCH: ``$client->patch('http://httpbin.org/put', [/** options **/])``
For example:
.. code-block:: php
$response = $client->patch('http://httpbin.org/patch', ['body' => 'content']);
Request URI
-----------
The request URI is represented by a ``Psr\Http\Message\UriInterface`` object.
Guzzle provides an implementation of this interface using the
``GuzzleHttp\Psr7\Uri`` class.
When creating a request, you can provide the URI as a string or an instance of
``Psr\Http\Message\UriInterface``.
.. code-block:: php
$response = $client->request('GET', 'http://httpbin.org/get?q=foo');
Scheme
------
The `scheme <http://tools.ietf.org/html/rfc3986#section-3.1>`_ of a request
specifies the protocol to use when sending the request. When using Guzzle, the
scheme can be set to "http" or "https".
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org');
echo $request->getUri()->getScheme(); // http
echo $request->getUri(); // http://httpbin.org
Host
----
The host is accessible using the URI owned by the request or by accessing the
Host header.
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org');
echo $request->getUri()->getHost(); // httpbin.org
echo $request->getHeader('Host'); // httpbin.org
Port
----
No port is necessary when using the "http" or "https" schemes.
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org:8080');
echo $request->getUri()->getPort(); // 8080
echo $request->getUri(); // http://httpbin.org:8080
Path
----
The path of a request is accessible via the URI object.
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org/get');
echo $request->getUri()->getPath(); // /get
The contents of the path will be automatically filtered to ensure that only
allowed characters are present in the path. Any characters that are not allowed
in the path will be percent-encoded according to
`RFC 3986 section 3.3 <https://tools.ietf.org/html/rfc3986#section-3.3>`_
Query string
------------
The query string of a request can be accessed using the ``getQuery()`` of the
URI object owned by the request.
.. code-block:: php
$request = new Request('GET', 'http://httpbin.org/?foo=bar');
echo $request->getUri()->getQuery(); // foo=bar
The contents of the query string will be automatically filtered to ensure that
only allowed characters are present in the query string. Any characters that
are not allowed in the query string will be percent-encoded according to
`RFC 3986 section 3.4 <https://tools.ietf.org/html/rfc3986#section-3.4>`_
Responses
=========
Responses are the HTTP messages a client receives from a server after sending
an HTTP request message.
Start-Line
----------
The start-line of a response contains the protocol and protocol version,
status code, and reason phrase.
.. code-block:: php
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://httpbin.org/get');
echo $response->getStatusCode(); // 200
echo $response->getReasonPhrase(); // OK
echo $response->getProtocolVersion(); // 1.1
Body
----
As described earlier, you can get the body of a response using the
``getBody()`` method.
.. code-block:: php
$body = $response->getBody();
echo $body;
// Cast to a string: { ... }
$body->seek(0);
// Rewind the body
$body->read(1024);
// Read bytes of the body
Streams
=======
Guzzle uses PSR-7 stream objects to represent request and response message
bodies. These stream objects allow you to work with various types of data all
using a common interface.
HTTP messages consist of a start-line, headers, and a body. The body of an HTTP
message can be very small or extremely large. Attempting to represent the body
of a message as a string can easily consume more memory than intended because
the body must be stored completely in memory. Attempting to store the body of a
request or response in memory would preclude the use of that implementation from
being able to work with large message bodies. The StreamInterface is used in
order to hide the implementation details of where a stream of data is read from
or written to.
The PSR-7 ``Psr\Http\Message\StreamInterface`` exposes several methods
that enable streams to be read from, written to, and traversed effectively.
Streams expose their capabilities using three methods: ``isReadable()``,
``isWritable()``, and ``isSeekable()``. These methods can be used by stream
collaborators to determine if a stream is capable of their requirements.
Each stream instance has various capabilities: they can be read-only,
write-only, read-write, allow arbitrary random access (seeking forwards or
backwards to any location), or only allow sequential access (for example in the
case of a socket or pipe).
Guzzle uses the ``guzzlehttp/psr7`` package to provide stream support. More
information on using streams, creating streams, converting streams to PHP
stream resource, and stream decorators can be found in the
`Guzzle PSR-7 documentation <https://github.com/guzzle/psr7/blob/master/README.md>`_.
Creating Streams
----------------
The best way to create a stream is using the ``GuzzleHttp\Psr7\stream_for``
function. This function accepts strings, resources returned from ``fopen()``,
an object that implements ``__toString()``, iterators, callables, and instances
of ``Psr\Http\Message\StreamInterface``.
.. code-block:: php
use GuzzleHttp\Psr7;
$stream = Psr7\stream_for('string data');
echo $stream;
// string data
echo $stream->read(3);
// str
echo $stream->getContents();
// ing data
var_export($stream->eof());
// true
var_export($stream->tell());
// 11
You can create streams from iterators. The iterator can yield any number of
bytes per iteration. Any excess bytes returned by the iterator that were not
requested by a stream consumer will be buffered until a subsequent read.
.. code-block:: php
use GuzzleHttp\Psr7;
$generator = function ($bytes) {
for ($i = 0; $i < $bytes; $i++) {
yield '.';
}
};
$iter = $generator(1024);
$stream = Psr7\stream_for($iter);
echo $stream->read(3); // ...
Metadata
--------
Streams expose stream metadata through the ``getMetadata()`` method. This
method provides the data you would retrieve when calling PHP's
`stream_get_meta_data() function <http://php.net/manual/en/function.stream-get-meta-data.php>`_,
and can optionally expose other custom data.
.. code-block:: php
use GuzzleHttp\Psr7;
$resource = fopen('/path/to/file', 'r');
$stream = Psr7\stream_for($resource);
echo $stream->getMetadata('uri');
// /path/to/file
var_export($stream->isReadable());
// true
var_export($stream->isWritable());
// false
var_export($stream->isSeekable());
// true
Stream Decorators
-----------------
Adding custom functionality to streams is very simple with stream decorators.
Guzzle provides several built-in decorators that provide additional stream
functionality.
- `AppendStream <https://github.com/guzzle/psr7#appendstream>`_
- `BufferStream <https://github.com/guzzle/psr7#bufferstream>`_
- `CachingStream <https://github.com/guzzle/psr7#cachingstream>`_
- `DroppingStream <https://github.com/guzzle/psr7#droppingstream>`_
- `FnStream <https://github.com/guzzle/psr7#fnstream>`_
- `InflateStream <https://github.com/guzzle/psr7#inflatestream>`_
- `LazyOpenStream <https://github.com/guzzle/psr7#lazyopenstream>`_
- `LimitStream <https://github.com/guzzle/psr7#limitstream>`_
- `MultipartStream <https://github.com/guzzle/psr7#multipartstream>`_
- `NoSeekStream <https://github.com/guzzle/psr7#noseekstream>`_
- `PumpStream <https://github.com/guzzle/psr7#pumpstream>`_

View File

@ -0,0 +1,624 @@
==========
Quickstart
==========
This page provides a quick introduction to Guzzle and introductory examples.
If you have not already installed, Guzzle, head over to the :ref:`installation`
page.
Making a Request
================
You can send requests with Guzzle using a ``GuzzleHttp\ClientInterface``
object.
Creating a Client
-----------------
.. code-block:: php
use GuzzleHttp\Client;
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'http://httpbin.org',
// You can set any number of default request options.
'timeout' => 2.0,
]);
Clients are immutable in Guzzle 6, which means that you cannot change the defaults used by a client after it's created.
The client constructor accepts an associative array of options:
``base_uri``
(string|UriInterface) Base URI of the client that is merged into relative
URIs. Can be a string or instance of UriInterface. When a relative URI
is provided to a client, the client will combine the base URI with the
relative URI using the rules described in
`RFC 3986, section 2 <http://tools.ietf.org/html/rfc3986#section-5.2>`_.
.. code-block:: php
// Create a client with a base URI
$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
// Send a request to https://foo.com/api/test
$response = $client->request('GET', 'test');
// Send a request to https://foo.com/root
$response = $client->request('GET', '/root');
Don't feel like reading RFC 3986? Here are some quick examples on how a
``base_uri`` is resolved with another URI.
======================= ================== ===============================
base_uri URI Result
======================= ================== ===============================
``http://foo.com`` ``/bar`` ``http://foo.com/bar``
``http://foo.com/foo`` ``/bar`` ``http://foo.com/bar``
``http://foo.com/foo`` ``bar`` ``http://foo.com/bar``
``http://foo.com/foo/`` ``bar`` ``http://foo.com/foo/bar``
``http://foo.com`` ``http://baz.com`` ``http://baz.com``
``http://foo.com/?bar`` ``bar`` ``http://foo.com/bar``
======================= ================== ===============================
``handler``
(callable) Function that transfers HTTP requests over the wire. The
function is called with a ``Psr7\Http\Message\RequestInterface`` and array
of transfer options, and must return a
``GuzzleHttp\Promise\PromiseInterface`` that is fulfilled with a
``Psr7\Http\Message\ResponseInterface`` on success.
``...``
(mixed) All other options passed to the constructor are used as default
request options with every request created by the client.
Sending Requests
----------------
Magic methods on the client make it easy to send synchronous requests:
.. code-block:: php
$response = $client->get('http://httpbin.org/get');
$response = $client->delete('http://httpbin.org/delete');
$response = $client->head('http://httpbin.org/get');
$response = $client->options('http://httpbin.org/get');
$response = $client->patch('http://httpbin.org/patch');
$response = $client->post('http://httpbin.org/post');
$response = $client->put('http://httpbin.org/put');
You can create a request and then send the request with the client when you're
ready:
.. code-block:: php
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http://httpbin.org/put');
$response = $client->send($request, ['timeout' => 2]);
Client objects provide a great deal of flexibility in how request are
transferred including default request options, default handler stack middleware
that are used by each request, and a base URI that allows you to send requests
with relative URIs.
You can find out more about client middleware in the
:doc:`handlers-and-middleware` page of the documentation.
Async Requests
--------------
You can send asynchronous requests using the magic methods provided by a client:
.. code-block:: php
$promise = $client->getAsync('http://httpbin.org/get');
$promise = $client->deleteAsync('http://httpbin.org/delete');
$promise = $client->headAsync('http://httpbin.org/get');
$promise = $client->optionsAsync('http://httpbin.org/get');
$promise = $client->patchAsync('http://httpbin.org/patch');
$promise = $client->postAsync('http://httpbin.org/post');
$promise = $client->putAsync('http://httpbin.org/put');
You can also use the `sendAsync()` and `requestAsync()` methods of a client:
.. code-block:: php
use GuzzleHttp\Psr7\Request;
// Create a PSR-7 request object to send
$headers = ['X-Foo' => 'Bar'];
$body = 'Hello!';
$request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
$promise = $client->sendAsync($request);
// Or, if you don't need to pass in a request instance:
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
The promise returned by these methods implements the
`Promises/A+ spec <https://promisesaplus.com/>`_, provided by the
`Guzzle promises library <https://github.com/guzzle/promises>`_. This means
that you can chain ``then()`` calls off of the promise. These then calls are
either fulfilled with a successful ``Psr\Http\Message\ResponseInterface`` or
rejected with an exception.
.. code-block:: php
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
Concurrent requests
-------------------
You can send multiple requests concurrently using promises and asynchronous
requests.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
$client = new Client(['base_uri' => 'http://httpbin.org/']);
// Initiate each request but do not block
$promises = [
'image' => $client->getAsync('/image'),
'png' => $client->getAsync('/image/png'),
'jpeg' => $client->getAsync('/image/jpeg'),
'webp' => $client->getAsync('/image/webp')
];
// Wait for the requests to complete; throws a ConnectException
// if any of the requests fail
$responses = Promise\unwrap($promises);
// Wait for the requests to complete, even if some of them fail
$responses = Promise\settle($promises)->wait();
// You can access each response using the key of the promise
echo $responses['image']->getHeader('Content-Length')[0];
echo $responses['png']->getHeader('Content-Length')[0];
You can use the ``GuzzleHttp\Pool`` object when you have an indeterminate
amount of requests you wish to send.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
$client = new Client();
$requests = function ($total) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield new Request('GET', $uri);
}
};
$pool = new Pool($client, $requests(100), [
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) {
// this is delivered each successful response
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
Or using a closure that will return a promise once the pool calls the closure.
.. code-block:: php
$client = new Client();
$requests = function ($total) use ($client) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i < $total; $i++) {
yield function() use ($client, $uri) {
return $client->getAsync($uri);
};
}
};
$pool = new Pool($client, $requests(100));
Using Responses
===============
In the previous examples, we retrieved a ``$response`` variable or we were
delivered a response from a promise. The response object implements a PSR-7
response, ``Psr\Http\Message\ResponseInterface``, and contains lots of
helpful information.
You can get the status code and reason phrase of the response:
.. code-block:: php
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
You can retrieve headers from the response:
.. code-block:: php
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}
// Get a header from the response.
echo $response->getHeader('Content-Length')[0];
// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
The body of a response can be retrieved using the ``getBody`` method. The body
can be used as a string, cast to a string, or used as a stream like object.
.. code-block:: php
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();
Query String Parameters
=======================
You can provide query string parameters with a request in several ways.
You can set query string parameters in the request's URI:
.. code-block:: php
$response = $client->request('GET', 'http://httpbin.org?foo=bar');
You can specify the query string parameters using the ``query`` request
option as an array.
.. code-block:: php
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Providing the option as an array will use PHP's ``http_build_query`` function
to format the query string.
And finally, you can provide the ``query`` request option as a string.
.. code-block:: php
$client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
Uploading Data
==============
Guzzle provides several methods for uploading data.
You can send requests that contain a stream of data by passing a string,
resource returned from ``fopen``, or an instance of a
``Psr\Http\Message\StreamInterface`` to the ``body`` request option.
.. code-block:: php
// Provide the body as a string.
$r = $client->request('POST', 'http://httpbin.org/post', [
'body' => 'raw data'
]);
// Provide an fopen resource.
$body = fopen('/path/to/file', 'r');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
// Use the stream_for() function to create a PSR-7 stream.
$body = \GuzzleHttp\Psr7\stream_for('hello!');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
An easy way to upload JSON data and set the appropriate header is using the
``json`` request option:
.. code-block:: php
$r = $client->request('PUT', 'http://httpbin.org/put', [
'json' => ['foo' => 'bar']
]);
POST/Form Requests
------------------
In addition to specifying the raw data of a request using the ``body`` request
option, Guzzle provides helpful abstractions over sending POST data.
Sending form fields
~~~~~~~~~~~~~~~~~~~
Sending ``application/x-www-form-urlencoded`` POST requests requires that you
specify the POST fields as an array in the ``form_params`` request options.
.. code-block:: php
$response = $client->request('POST', 'http://httpbin.org/post', [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
Sending form files
~~~~~~~~~~~~~~~~~~
You can send files along with a form (``multipart/form-data`` POST requests),
using the ``multipart`` request option. ``multipart`` accepts an array of
associative arrays, where each associative array contains the following keys:
- name: (required, string) key mapping to the form field name.
- contents: (required, mixed) Provide a string to send the contents of the
file as a string, provide an fopen resource to stream the contents from a
PHP stream, or provide a ``Psr\Http\Message\StreamInterface`` to stream
the contents from a PSR-7 stream.
.. code-block:: php
$response = $client->request('POST', 'http://httpbin.org/post', [
'multipart' => [
[
'name' => 'field_name',
'contents' => 'abc'
],
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'other_file',
'contents' => 'hello',
'filename' => 'filename.txt',
'headers' => [
'X-Foo' => 'this is an extra header to include'
]
]
]
]);
Cookies
=======
Guzzle can maintain a cookie session for you if instructed using the
``cookies`` request option. When sending a request, the ``cookies`` option
must be set to an instance of ``GuzzleHttp\Cookie\CookieJarInterface``.
.. code-block:: php
// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
'cookies' => $jar
]);
You can set ``cookies`` to ``true`` in a client constructor if you would like
to use a shared cookie jar for all requests.
.. code-block:: php
// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');
Different implementations exist for the ``GuzzleHttp\Cookie\CookieJarInterface``
:
- The ``GuzzleHttp\Cookie\CookieJar`` class stores cookies as an array.
- The ``GuzzleHttp\Cookie\FileCookieJar`` class persists non-session cookies
using a JSON formatted file.
- The ``GuzzleHttp\Cookie\SessionCookieJar`` class persists cookies in the
client session.
You can manually set cookies into a cookie jar with the named constructor
``fromArray(array $cookies, $domain)``.
.. code-block:: php
$jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
[
'some_cookie' => 'foo',
'other_cookie' => 'barbaz1234'
],
'example.org'
);
You can get a cookie by its name with the ``getCookieByName($name)`` method
which returns a ``GuzzleHttp\Cookie\SetCookie`` instance.
.. code-block:: php
$cookie = $jar->getCookieByName('some_cookie');
$cookie->getValue(); // 'foo'
$cookie->getDomain(); // 'example.org'
$cookie->getExpires(); // expiration date as a Unix timestamp
The cookies can be also fetched into an array thanks to the `toArray()` method.
The ``GuzzleHttp\Cookie\CookieJarInterface`` interface extends
``Traversable`` so it can be iterated in a foreach loop.
Redirects
=========
Guzzle will automatically follow redirects unless you tell it not to. You can
customize the redirect behavior using the ``allow_redirects`` request option.
- Set to ``true`` to enable normal redirects with a maximum number of 5
redirects. This is the default setting.
- Set to ``false`` to disable redirects.
- Pass an associative array containing the 'max' key to specify the maximum
number of redirects and optionally provide a 'strict' key value to specify
whether or not to use strict RFC compliant redirects (meaning redirect POST
requests with POST requests vs. doing what most browsers do which is
redirect POST requests with GET requests).
.. code-block:: php
$response = $client->request('GET', 'http://github.com');
echo $response->getStatusCode();
// 200
The following example shows that redirects can be disabled.
.. code-block:: php
$response = $client->request('GET', 'http://github.com', [
'allow_redirects' => false
]);
echo $response->getStatusCode();
// 301
Exceptions
==========
**Tree View**
The following tree view describes how the Guzzle Exceptions depend
on each other.
.. code-block:: none
. \RuntimeException
├── SeekException (implements GuzzleException)
└── TransferException (implements GuzzleException)
└── RequestException
├── BadResponseException
│   ├── ServerException
│ └── ClientException
├── ConnectException
└── TooManyRedirectsException
Guzzle throws exceptions for errors that occur during a transfer.
- In the event of a networking error (connection timeout, DNS errors, etc.),
a ``GuzzleHttp\Exception\RequestException`` is thrown. This exception
extends from ``GuzzleHttp\Exception\TransferException``. Catching this
exception will catch any exception that can be thrown while transferring
requests.
.. code-block:: php
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$client->request('GET', 'https://github.com/_abc_123_404');
} catch (RequestException $e) {
echo Psr7\str($e->getRequest());
if ($e->hasResponse()) {
echo Psr7\str($e->getResponse());
}
}
- A ``GuzzleHttp\Exception\ConnectException`` exception is thrown in the
event of a networking error. This exception extends from
``GuzzleHttp\Exception\RequestException``.
- A ``GuzzleHttp\Exception\ClientException`` is thrown for 400
level errors if the ``http_errors`` request option is set to true. This
exception extends from ``GuzzleHttp\Exception\BadResponseException`` and
``GuzzleHttp\Exception\BadResponseException`` extends from
``GuzzleHttp\Exception\RequestException``.
.. code-block:: php
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
try {
$client->request('GET', 'https://github.com/_abc_123_404');
} catch (ClientException $e) {
echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}
- A ``GuzzleHttp\Exception\ServerException`` is thrown for 500 level
errors if the ``http_errors`` request option is set to true. This
exception extends from ``GuzzleHttp\Exception\BadResponseException``.
- A ``GuzzleHttp\Exception\TooManyRedirectsException`` is thrown when too
many redirects are followed. This exception extends from ``GuzzleHttp\Exception\RequestException``.
All of the above exceptions extend from
``GuzzleHttp\Exception\TransferException``.
Environment Variables
=====================
Guzzle exposes a few environment variables that can be used to customize the
behavior of the library.
``GUZZLE_CURL_SELECT_TIMEOUT``
Controls the duration in seconds that a curl_multi_* handler will use when
selecting on curl handles using ``curl_multi_select()``. Some systems
have issues with PHP's implementation of ``curl_multi_select()`` where
calling this function always results in waiting for the maximum duration of
the timeout.
``HTTP_PROXY``
Defines the proxy to use when sending requests using the "http" protocol.
Note: because the HTTP_PROXY variable may contain arbitrary user input on some (CGI) environments, the variable is only used on the CLI SAPI. See https://httpoxy.org for more information.
``HTTPS_PROXY``
Defines the proxy to use when sending requests using the "https" protocol.
``NO_PROXY``
Defines URLs for which a proxy should not be used. See :ref:`proxy-option` for usage.
Relevant ini Settings
---------------------
Guzzle can utilize PHP ini settings when configuring clients.
``openssl.cafile``
Specifies the path on disk to a CA file in PEM format to use when sending
requests over "https". See: https://wiki.php.net/rfc/tls-peer-verification#phpini_defaults

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
Sphinx>=1.3.0,<1.4.0
guzzle_sphinx_theme>=0.7.0,<0.8.0

View File

@ -0,0 +1,196 @@
======================
Testing Guzzle Clients
======================
Guzzle provides several tools that will enable you to easily mock the HTTP
layer without needing to send requests over the internet.
* Mock handler
* History middleware
* Node.js web server for integration testing
Mock Handler
============
When testing HTTP clients, you often need to simulate specific scenarios like
returning a successful response, returning an error, or returning specific
responses in a certain order. Because unit tests need to be predictable, easy
to bootstrap, and fast, hitting an actual remote API is a test smell.
Guzzle provides a mock handler that can be used to fulfill HTTP requests with
a response or exception by shifting return values off of a queue.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
// Create a mock and queue two responses.
$mock = new MockHandler([
new Response(200, ['X-Foo' => 'Bar'], 'Hello, World'),
new Response(202, ['Content-Length' => 0]),
new RequestException('Error Communicating with Server', new Request('GET', 'test'))
]);
$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);
// The first request is intercepted with the first response.
$response = $client->request('GET', '/');
echo $response->getStatusCode();
//> 200
echo $response->getBody();
//> Hello, World
// The second request is intercepted with the second response.
echo $client->request('GET', '/')->getStatusCode();
//> 202
// Reset the queue and queue up a new response
$mock->reset();
$mock->append(new Response(201));
// As the mock was reset, the new response is the 201 CREATED,
// instead of the previously queued RequestException
echo $client->request('GET', '/')->getStatusCode();
//> 201
When no more responses are in the queue and a request is sent, an
``OutOfBoundsException`` is thrown.
History Middleware
==================
When using things like the ``Mock`` handler, you often need to know if the
requests you expected to send were sent exactly as you intended. While the mock
handler responds with mocked responses, the history middleware maintains a
history of the requests that were sent by a client.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
$container = [];
$history = Middleware::history($container);
$handlerStack = HandlerStack::create();
// or $handlerStack = HandlerStack::create($mock); if using the Mock handler.
// Add the history middleware to the handler stack.
$handlerStack->push($history);
$client = new Client(['handler' => $handlerStack]);
$client->request('GET', 'http://httpbin.org/get');
$client->request('HEAD', 'http://httpbin.org/get');
// Count the number of transactions
echo count($container);
//> 2
// Iterate over the requests and responses
foreach ($container as $transaction) {
echo $transaction['request']->getMethod();
//> GET, HEAD
if ($transaction['response']) {
echo $transaction['response']->getStatusCode();
//> 200, 200
} elseif ($transaction['error']) {
echo $transaction['error'];
//> exception
}
var_dump($transaction['options']);
//> dumps the request options of the sent request.
}
Test Web Server
===============
Using mock responses is almost always enough when testing a web service client.
When implementing custom :doc:`HTTP handlers <handlers-and-middleware>`, you'll
need to send actual HTTP requests in order to sufficiently test the handler.
However, a best practice is to contact a local web server rather than a server
over the internet.
- Tests are more reliable
- Tests do not require a network connection
- Tests have no external dependencies
Using the test server
---------------------
.. warning::
The following functionality is provided to help developers of Guzzle
develop HTTP handlers. There is no promise of backwards compatibility
when it comes to the node.js test server or the ``GuzzleHttp\Tests\Server``
class. If you are using the test server or ``Server`` class outside of
guzzlehttp/guzzle, then you will need to configure autoloading and
ensure the web server is started manually.
.. hint::
You almost never need to use this test web server. You should only ever
consider using it when developing HTTP handlers. The test web server
is not necessary for mocking requests. For that, please use the
Mock handler and history middleware.
Guzzle ships with a node.js test server that receives requests and returns
responses from a queue. The test server exposes a simple API that is used to
enqueue responses and inspect the requests that it has received.
Any operation on the ``Server`` object will ensure that
the server is running and wait until it is able to receive requests before
returning.
``GuzzleHttp\Tests\Server`` provides a static interface to the test server. You
can queue an HTTP response or an array of responses by calling
``Server::enqueue()``. This method accepts an array of
``Psr\Http\Message\ResponseInterface`` and ``Exception`` objects.
.. code-block:: php
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Server;
// Start the server and queue a response
Server::enqueue([
new Response(200, ['Content-Length' => 0])
]);
$client = new Client(['base_uri' => Server::$url]);
echo $client->request('GET', '/foo')->getStatusCode();
// 200
When a response is queued on the test server, the test server will remove any
previously queued responses. As the server receives requests, queued responses
are dequeued and returned to the request. When the queue is empty, the server
will return a 500 response.
You can inspect the requests that the server has retrieved by calling
``Server::received()``.
.. code-block:: php
foreach (Server::received() as $response) {
echo $response->getStatusCode();
}
You can clear the list of received requests from the web server using the
``Server::flush()`` method.
.. code-block:: php
Server::flush();
echo count(Server::received());
// 0

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
includes:
- phpstan-baseline.neon
parameters:
level: max
paths:
- src

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="./tests/bootstrap.php"
backupGlobals="true"
colors="true"
executionOrder="random"
>
<testsuites>
<testsuite name="Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src</directory>
<exclude>
<directory suffix="Interface.php">src/</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,811 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
class ClientTest extends TestCase
{
public function testUsesDefaultHandler()
{
$client = new Client();
Server::enqueue([new Response(200, ['Content-Length' => 0])]);
$response = $client->get(Server::$url);
self::assertSame(200, $response->getStatusCode());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Magic request methods require a URI and optional options array
*/
public function testValidatesArgsForMagicMethods()
{
$client = new Client();
$client->get();
}
public function testCanSendMagicAsyncRequests()
{
$client = new Client();
Server::flush();
Server::enqueue([new Response(200, ['Content-Length' => 2], 'hi')]);
$p = $client->getAsync(Server::$url, ['query' => ['test' => 'foo']]);
self::assertInstanceOf(PromiseInterface::class, $p);
self::assertSame(200, $p->wait()->getStatusCode());
$received = Server::received(true);
self::assertCount(1, $received);
self::assertSame('test=foo', $received[0]->getUri()->getQuery());
}
public function testCanSendSynchronously()
{
$client = new Client(['handler' => new MockHandler([new Response()])]);
$request = new Request('GET', 'http://example.com');
$r = $client->send($request);
self::assertInstanceOf(ResponseInterface::class, $r);
self::assertSame(200, $r->getStatusCode());
}
public function testClientHasOptions()
{
$client = new Client([
'base_uri' => 'http://foo.com',
'timeout' => 2,
'headers' => ['bar' => 'baz'],
'handler' => new MockHandler()
]);
$base = $client->getConfig('base_uri');
self::assertSame('http://foo.com', (string) $base);
self::assertInstanceOf(Uri::class, $base);
self::assertNotNull($client->getConfig('handler'));
self::assertSame(2, $client->getConfig('timeout'));
self::assertArrayHasKey('timeout', $client->getConfig());
self::assertArrayHasKey('headers', $client->getConfig());
}
public function testCanMergeOnBaseUri()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'base_uri' => 'http://foo.com/bar/',
'handler' => $mock
]);
$client->get('baz');
self::assertSame(
'http://foo.com/bar/baz',
(string)$mock->getLastRequest()->getUri()
);
}
public function testCanMergeOnBaseUriWithRequest()
{
$mock = new MockHandler([new Response(), new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://foo.com/bar/'
]);
$client->request('GET', new Uri('baz'));
self::assertSame(
'http://foo.com/bar/baz',
(string) $mock->getLastRequest()->getUri()
);
$client->request('GET', new Uri('baz'), ['base_uri' => 'http://example.com/foo/']);
self::assertSame(
'http://example.com/foo/baz',
(string) $mock->getLastRequest()->getUri(),
'Can overwrite the base_uri through the request options'
);
}
public function testCanUseRelativeUriWithSend()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://bar.com'
]);
self::assertSame('http://bar.com', (string) $client->getConfig('base_uri'));
$request = new Request('GET', '/baz');
$client->send($request);
self::assertSame(
'http://bar.com/baz',
(string) $mock->getLastRequest()->getUri()
);
}
public function testMergesDefaultOptionsAndDoesNotOverwriteUa()
{
$c = new Client(['headers' => ['User-agent' => 'foo']]);
self::assertSame(['User-agent' => 'foo'], $c->getConfig('headers'));
self::assertInternalType('array', $c->getConfig('allow_redirects'));
self::assertTrue($c->getConfig('http_errors'));
self::assertTrue($c->getConfig('decode_content'));
self::assertTrue($c->getConfig('verify'));
}
public function testDoesNotOverwriteHeaderWithDefault()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock
]);
$c->get('http://example.com', ['headers' => ['User-Agent' => 'bar']]);
self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testDoesNotOverwriteHeaderWithDefaultInRequest()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock
]);
$request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
$c->send($request);
self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testDoesOverwriteHeaderWithSetRequestOption()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock
]);
$request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
$c->send($request, ['headers' => ['User-Agent' => 'YO']]);
self::assertSame('YO', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testCanUnsetRequestOptionWithNull()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['foo' => 'bar'],
'handler' => $mock
]);
$c->get('http://example.com', ['headers' => null]);
self::assertFalse($mock->getLastRequest()->hasHeader('foo'));
}
public function testRewriteExceptionsToHttpErrors()
{
$client = new Client(['handler' => new MockHandler([new Response(404)])]);
$res = $client->get('http://foo.com', ['exceptions' => false]);
self::assertSame(404, $res->getStatusCode());
}
public function testRewriteSaveToToSink()
{
$r = Psr7\stream_for(fopen('php://temp', 'r+'));
$mock = new MockHandler([new Response(200, [], 'foo')]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['save_to' => $r]);
self::assertSame($r, $mock->getLastOptions()['sink']);
}
public function testAllowRedirectsCanBeTrue()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com', ['allow_redirects' => true]);
self::assertInternalType('array', $mock->getLastOptions()['allow_redirects']);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage allow_redirects must be true, false, or array
*/
public function testValidatesAllowRedirects()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com', ['allow_redirects' => 'foo']);
}
/**
* @expectedException \GuzzleHttp\Exception\ClientException
*/
public function testThrowsHttpErrorsByDefault()
{
$mock = new MockHandler([new Response(404)]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com');
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface
*/
public function testValidatesCookies()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com', ['cookies' => 'foo']);
}
public function testSetCookieToTrueUsesSharedJar()
{
$mock = new MockHandler([
new Response(200, ['Set-Cookie' => 'foo=bar']),
new Response()
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler, 'cookies' => true]);
$client->get('http://foo.com');
$client->get('http://foo.com');
self::assertSame('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
}
public function testSetCookieToJar()
{
$mock = new MockHandler([
new Response(200, ['Set-Cookie' => 'foo=bar']),
new Response()
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$jar = new CookieJar();
$client->get('http://foo.com', ['cookies' => $jar]);
$client->get('http://foo.com', ['cookies' => $jar]);
self::assertSame('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
}
public function testCanDisableContentDecoding()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['decode_content' => false]);
$last = $mock->getLastRequest();
self::assertFalse($last->hasHeader('Accept-Encoding'));
self::assertFalse($mock->getLastOptions()['decode_content']);
}
public function testCanSetContentDecodingToValue()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['decode_content' => 'gzip']);
$last = $mock->getLastRequest();
self::assertSame('gzip', $last->getHeaderLine('Accept-Encoding'));
self::assertSame('gzip', $mock->getLastOptions()['decode_content']);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesHeaders()
{
$mock = new MockHandler();
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['headers' => 'foo']);
}
public function testAddsBody()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['body' => 'foo']);
$last = $mock->getLastRequest();
self::assertSame('foo', (string) $last->getBody());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesQuery()
{
$mock = new MockHandler();
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => false]);
}
public function testQueryCanBeString()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => 'foo']);
self::assertSame('foo', $mock->getLastRequest()->getUri()->getQuery());
}
public function testQueryCanBeArray()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => ['foo' => 'bar baz']]);
self::assertSame('foo=bar%20baz', $mock->getLastRequest()->getUri()->getQuery());
}
public function testCanAddJsonData()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['json' => ['foo' => 'bar']]);
$last = $mock->getLastRequest();
self::assertSame('{"foo":"bar"}', (string) $mock->getLastRequest()->getBody());
self::assertSame('application/json', $last->getHeaderLine('Content-Type'));
}
public function testCanAddJsonDataWithoutOverwritingContentType()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, [
'headers' => ['content-type' => 'foo'],
'json' => 'a'
]);
$last = $mock->getLastRequest();
self::assertSame('"a"', (string) $mock->getLastRequest()->getBody());
self::assertSame('foo', $last->getHeaderLine('Content-Type'));
}
public function testCanAddJsonDataWithNullHeader()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, [
'headers' => null,
'json' => 'a'
]);
$last = $mock->getLastRequest();
self::assertSame('"a"', (string) $mock->getLastRequest()->getBody());
self::assertSame('application/json', $last->getHeaderLine('Content-Type'));
}
public function testAuthCanBeTrue()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => false]);
$last = $mock->getLastRequest();
self::assertFalse($last->hasHeader('Authorization'));
}
public function testAuthCanBeArrayForBasicAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b']]);
$last = $mock->getLastRequest();
self::assertSame('Basic YTpi', $last->getHeaderLine('Authorization'));
}
public function testAuthCanBeArrayForDigestAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b', 'digest']]);
$last = $mock->getLastOptions();
self::assertSame([
CURLOPT_HTTPAUTH => 2,
CURLOPT_USERPWD => 'a:b'
], $last['curl']);
}
public function testAuthCanBeArrayForNtlmAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b', 'ntlm']]);
$last = $mock->getLastOptions();
self::assertSame([
CURLOPT_HTTPAUTH => 8,
CURLOPT_USERPWD => 'a:b'
], $last['curl']);
}
public function testAuthCanBeCustomType()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => 'foo']);
$last = $mock->getLastOptions();
self::assertSame('foo', $last['auth']);
}
public function testCanAddFormParams()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'form_params' => [
'foo' => 'bar bam',
'baz' => ['boo' => 'qux']
]
]);
$last = $mock->getLastRequest();
self::assertSame(
'application/x-www-form-urlencoded',
$last->getHeaderLine('Content-Type')
);
self::assertSame(
'foo=bar+bam&baz%5Bboo%5D=qux',
(string) $last->getBody()
);
}
public function testFormParamsEncodedProperly()
{
$separator = ini_get('arg_separator.output');
ini_set('arg_separator.output', '&amp;');
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'form_params' => [
'foo' => 'bar bam',
'baz' => ['boo' => 'qux']
]
]);
$last = $mock->getLastRequest();
self::assertSame(
'foo=bar+bam&baz%5Bboo%5D=qux',
(string) $last->getBody()
);
ini_set('arg_separator.output', $separator);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresThatFormParamsAndMultipartAreExclusive()
{
$client = new Client(['handler' => function () {
}]);
$client->post('http://foo.com', [
'form_params' => ['foo' => 'bar bam'],
'multipart' => []
]);
}
public function testCanSendMultipart()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'multipart' => [
[
'name' => 'foo',
'contents' => 'bar'
],
[
'name' => 'test',
'contents' => fopen(__FILE__, 'r')
]
]
]);
$last = $mock->getLastRequest();
self::assertContains(
'multipart/form-data; boundary=',
$last->getHeaderLine('Content-Type')
);
self::assertContains(
'Content-Disposition: form-data; name="foo"',
(string) $last->getBody()
);
self::assertContains('bar', (string) $last->getBody());
self::assertContains(
'Content-Disposition: form-data; name="foo"' . "\r\n",
(string) $last->getBody()
);
self::assertContains(
'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
(string) $last->getBody()
);
}
public function testCanSendMultipartWithExplicitBody()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->send(
new Request(
'POST',
'http://foo.com',
[],
new Psr7\MultipartStream(
[
[
'name' => 'foo',
'contents' => 'bar',
],
[
'name' => 'test',
'contents' => fopen(__FILE__, 'r'),
],
]
)
)
);
$last = $mock->getLastRequest();
self::assertContains(
'multipart/form-data; boundary=',
$last->getHeaderLine('Content-Type')
);
self::assertContains(
'Content-Disposition: form-data; name="foo"',
(string) $last->getBody()
);
self::assertContains('bar', (string) $last->getBody());
self::assertContains(
'Content-Disposition: form-data; name="foo"' . "\r\n",
(string) $last->getBody()
);
self::assertContains(
'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
(string) $last->getBody()
);
}
public function testUsesProxyEnvironmentVariables()
{
$http = getenv('HTTP_PROXY');
$https = getenv('HTTPS_PROXY');
$no = getenv('NO_PROXY');
$client = new Client();
self::assertNull($client->getConfig('proxy'));
putenv('HTTP_PROXY=127.0.0.1');
$client = new Client();
self::assertSame(
['http' => '127.0.0.1'],
$client->getConfig('proxy')
);
putenv('HTTPS_PROXY=127.0.0.2');
putenv('NO_PROXY=127.0.0.3, 127.0.0.4');
$client = new Client();
self::assertSame(
['http' => '127.0.0.1', 'https' => '127.0.0.2', 'no' => ['127.0.0.3','127.0.0.4']],
$client->getConfig('proxy')
);
putenv("HTTP_PROXY=$http");
putenv("HTTPS_PROXY=$https");
putenv("NO_PROXY=$no");
}
public function testRequestSendsWithSync()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->request('GET', 'http://foo.com');
self::assertTrue($mock->getLastOptions()['synchronous']);
}
public function testSendSendsWithSync()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->send(new Request('GET', 'http://foo.com'));
self::assertTrue($mock->getLastOptions()['synchronous']);
}
public function testCanSetCustomHandler()
{
$mock = new MockHandler([new Response(500)]);
$client = new Client(['handler' => $mock]);
$mock2 = new MockHandler([new Response(200)]);
self::assertSame(
200,
$client->send(new Request('GET', 'http://foo.com'), [
'handler' => $mock2
])->getStatusCode()
);
}
public function testProperlyBuildsQuery()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => ['foo' => 'bar', 'john' => 'doe']]);
self::assertSame('foo=bar&john=doe', $mock->getLastRequest()->getUri()->getQuery());
}
public function testSendSendsWithIpAddressAndPortAndHostHeaderInRequestTheHostShouldBePreserved()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['base_uri' => 'http://127.0.0.1:8585', 'handler' => $mockHandler]);
$request = new Request('GET', '/test', ['Host'=>'foo.com']);
$client->send($request);
self::assertSame('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
}
public function testSendSendsWithDomainAndHostHeaderInRequestTheHostShouldBePreserved()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['base_uri' => 'http://foo2.com', 'handler' => $mockHandler]);
$request = new Request('GET', '/test', ['Host'=>'foo.com']);
$client->send($request);
self::assertSame('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesSink()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->get('http://test.com', ['sink' => true]);
}
public function testHttpDefaultSchemeIfUriHasNone()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', '//example.org/test');
self::assertSame('http://example.org/test', (string) $mockHandler->getLastRequest()->getUri());
}
public function testOnlyAddSchemeWhenHostIsPresent()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'baz');
self::assertSame(
'baz',
(string) $mockHandler->getLastRequest()->getUri()
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testHandlerIsCallable()
{
new Client(['handler' => 'not_cllable']);
}
public function testResponseBodyAsString()
{
$responseBody = '{ "package": "guzzle" }';
$mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $responseBody)]);
$client = new Client(['handler' => $mock]);
$request = new Request('GET', 'http://foo.com');
$response = $client->send($request, ['json' => ['a' => 'b']]);
self::assertSame($responseBody, (string) $response->getBody());
}
public function testResponseContent()
{
$responseBody = '{ "package": "guzzle" }';
$mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $responseBody)]);
$client = new Client(['handler' => $mock]);
$request = new Request('POST', 'http://foo.com');
$response = $client->send($request, ['json' => ['a' => 'b']]);
self::assertSame($responseBody, $response->getBody()->getContents());
}
public function testIdnSupportDefaultValue()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$config = $client->getConfig();
self::assertTrue($config['idn_conversion']);
}
public function testIdnIsTranslatedToAsciiWhenConversionIsEnabled()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'https://яндекс.рф/images', ['idn_conversion' => true]);
$request = $mockHandler->getLastRequest();
self::assertSame('https://xn--d1acpjx3f.xn--p1ai/images', (string) $request->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $request->getHeaderLine('Host'));
}
public function testIdnStaysTheSameWhenConversionIsDisabled()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'https://яндекс.рф/images', ['idn_conversion' => false]);
$request = $mockHandler->getLastRequest();
self::assertSame('https://яндекс.рф/images', (string) $request->getUri());
self::assertSame('яндекс.рф', (string) $request->getHeaderLine('Host'));
}
/**
* @expectedException \GuzzleHttp\Exception\InvalidArgumentException
* @expectedExceptionMessage IDN conversion failed
*/
public function testExceptionOnInvalidIdn()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'https://-яндекс.рф/images', ['idn_conversion' => true]);
}
/**
* @depends testCanUseRelativeUriWithSend
* @depends testIdnSupportDefaultValue
*/
public function testIdnBaseUri()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://яндекс.рф',
]);
self::assertSame('http://яндекс.рф', (string) $client->getConfig('base_uri'));
$request = new Request('GET', '/baz');
$client->send($request);
self::assertSame('http://xn--d1acpjx3f.xn--p1ai/baz', (string) $mock->getLastRequest()->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $mock->getLastRequest()->getHeaderLine('Host'));
}
public function testIdnWithRedirect()
{
$mockHandler = new MockHandler([
new Response(302, ['Location' => 'http://www.tést.com/whatever']),
new Response()
]);
$handler = HandlerStack::create($mockHandler);
$requests = [];
$handler->push(Middleware::history($requests));
$client = new Client(['handler' => $handler]);
$client->request('GET', 'https://яндекс.рф/images', [
RequestOptions::ALLOW_REDIRECTS => [
'referer' => true,
'track_redirects' => true
],
'idn_conversion' => true
]);
$request = $mockHandler->getLastRequest();
self::assertSame('http://www.xn--tst-bma.com/whatever', (string) $request->getUri());
self::assertSame('www.xn--tst-bma.com', (string) $request->getHeaderLine('Host'));
$request = $requests[0]['request'];
self::assertSame('https://xn--d1acpjx3f.xn--p1ai/images', (string) $request->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $request->getHeaderLine('Host'));
}
}

View File

@ -0,0 +1,449 @@
<?php
namespace GuzzleHttp\Tests\CookieJar;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\Cookie\CookieJar
*/
class CookieJarTest extends TestCase
{
/** @var CookieJar */
private $jar;
public function setUp()
{
$this->jar = new CookieJar();
}
protected function getTestCookies()
{
return [
new SetCookie(['Name' => 'foo', 'Value' => 'bar', 'Domain' => 'foo.com', 'Path' => '/', 'Discard' => true]),
new SetCookie(['Name' => 'test', 'Value' => '123', 'Domain' => 'baz.com', 'Path' => '/foo', 'Expires' => 2]),
new SetCookie(['Name' => 'you', 'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', 'Expires' => time() + 1000])
];
}
public function testCreatesFromArray()
{
$jar = CookieJar::fromArray([
'foo' => 'bar',
'baz' => 'bam'
], 'example.com');
self::assertCount(2, $jar);
}
public function testEmptyJarIsCountable()
{
self::assertCount(0, new CookieJar());
}
public function testGetsCookiesByName()
{
$cookies = $this->getTestCookies();
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
$testCookie = $cookies[0];
self::assertEquals($testCookie, $this->jar->getCookieByName($testCookie->getName()));
self::assertNull($this->jar->getCookieByName("doesnotexist"));
self::assertNull($this->jar->getCookieByName(""));
}
/**
* Provides test data for cookie cookieJar retrieval
*/
public function getCookiesDataProvider()
{
return [
[['foo', 'baz', 'test', 'muppet', 'googoo'], '', '', '', false],
[['foo', 'baz', 'muppet', 'googoo'], '', '', '', true],
[['googoo'], 'www.example.com', '', '', false],
[['muppet', 'googoo'], 'test.y.example.com', '', '', false],
[['foo', 'baz'], 'example.com', '', '', false],
[['muppet'], 'x.y.example.com', '/acme/', '', false],
[['muppet'], 'x.y.example.com', '/acme/test/', '', false],
[['googoo'], 'x.y.example.com', '/test/acme/test/', '', false],
[['foo', 'baz'], 'example.com', '', '', false],
[['baz'], 'example.com', '', 'baz', false],
];
}
public function testStoresAndRetrievesCookies()
{
$cookies = $this->getTestCookies();
foreach ($cookies as $cookie) {
self::assertTrue($this->jar->setCookie($cookie));
}
self::assertCount(3, $this->jar);
self::assertCount(3, $this->jar->getIterator());
self::assertEquals($cookies, $this->jar->getIterator()->getArrayCopy());
}
public function testRemovesTemporaryCookies()
{
$cookies = $this->getTestCookies();
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
$this->jar->clearSessionCookies();
self::assertEquals(
[$cookies[1], $cookies[2]],
$this->jar->getIterator()->getArrayCopy()
);
}
public function testRemovesSelectively()
{
foreach ($this->getTestCookies() as $cookie) {
$this->jar->setCookie($cookie);
}
// Remove foo.com cookies
$this->jar->clear('foo.com');
self::assertCount(2, $this->jar);
// Try again, removing no further cookies
$this->jar->clear('foo.com');
self::assertCount(2, $this->jar);
// Remove bar.com cookies with path of /boo
$this->jar->clear('bar.com', '/boo');
self::assertCount(1, $this->jar);
// Remove cookie by name
$this->jar->clear(null, null, 'test');
self::assertCount(0, $this->jar);
}
public function testDoesNotAddIncompleteCookies()
{
self::assertFalse($this->jar->setCookie(new SetCookie()));
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => 'foo'
])));
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => false
])));
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => true
])));
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => 'foo',
'Domain' => 'foo.com'
])));
}
public function testDoesNotAddEmptyCookies()
{
self::assertFalse($this->jar->setCookie(new SetCookie([
'Name' => '',
'Domain' => 'foo.com',
'Value' => 0
])));
}
public function testDoesAddValidCookies()
{
self::assertTrue($this->jar->setCookie(new SetCookie([
'Name' => '0',
'Domain' => 'foo.com',
'Value' => 0
])));
self::assertTrue($this->jar->setCookie(new SetCookie([
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => 0
])));
self::assertTrue($this->jar->setCookie(new SetCookie([
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => 0.0
])));
self::assertTrue($this->jar->setCookie(new SetCookie([
'Name' => 'foo',
'Domain' => 'foo.com',
'Value' => '0'
])));
}
public function testOverwritesCookiesThatAreOlderOrDiscardable()
{
$t = time() + 1000;
$data = [
'Name' => 'foo',
'Value' => 'bar',
'Domain' => '.example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true,
'Discard' => true,
'Expires' => $t
];
// Make sure that the discard cookie is overridden with the non-discard
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$data['Discard'] = false;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertFalse($c[0]->getDiscard());
// Make sure it doesn't duplicate the cookie
$this->jar->setCookie(new SetCookie($data));
self::assertCount(1, $this->jar);
// Make sure the more future-ful expiration date supersede the other
$data['Expires'] = time() + 2000;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertNotEquals($t, $c[0]->getExpires());
}
public function testOverwritesCookiesThatHaveChanged()
{
$t = time() + 1000;
$data = [
'Name' => 'foo',
'Value' => 'bar',
'Domain' => '.example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true,
'Discard' => true,
'Expires' => $t
];
// Make sure that the discard cookie is overridden with the non-discard
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
$data['Value'] = 'boo';
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
// Changing the value plus a parameter also must overwrite the existing one
$data['Value'] = 'zoo';
$data['Secure'] = false;
self::assertTrue($this->jar->setCookie(new SetCookie($data)));
self::assertCount(1, $this->jar);
$c = $this->jar->getIterator()->getArrayCopy();
self::assertSame('zoo', $c[0]->getValue());
}
public function testAddsCookiesFromResponseWithRequest()
{
$response = new Response(200, [
'Set-Cookie' => "fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;"
]);
$request = new Request('GET', 'http://www.example.com');
$this->jar->extractCookies($request, $response);
self::assertCount(1, $this->jar);
}
public function getMatchingCookiesDataProvider()
{
return [
['https://example.com', 'foo=bar; baz=foobar'],
['http://example.com', ''],
['https://example.com:8912', 'foo=bar; baz=foobar'],
['https://foo.example.com', 'foo=bar; baz=foobar'],
['http://foo.example.com/test/acme/', 'googoo=gaga']
];
}
/**
* @dataProvider getMatchingCookiesDataProvider
*/
public function testReturnsCookiesMatchingRequests($url, $cookies)
{
$bag = [
new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true
]),
new SetCookie([
'Name' => 'baz',
'Value' => 'foobar',
'Domain' => 'example.com',
'Path' => '/',
'Max-Age' => '86400',
'Secure' => true
]),
new SetCookie([
'Name' => 'test',
'Value' => '123',
'Domain' => 'www.foobar.com',
'Path' => '/path/',
'Discard' => true
]),
new SetCookie([
'Name' => 'muppet',
'Value' => 'cookie_monster',
'Domain' => '.y.example.com',
'Path' => '/acme/',
'Expires' => time() + 86400
]),
new SetCookie([
'Name' => 'googoo',
'Value' => 'gaga',
'Domain' => '.example.com',
'Path' => '/test/acme/',
'Max-Age' => 1500
])
];
foreach ($bag as $cookie) {
$this->jar->setCookie($cookie);
}
$request = new Request('GET', $url);
$request = $this->jar->withCookieHeader($request);
self::assertSame($cookies, $request->getHeaderLine('Cookie'));
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Invalid cookie: Cookie name must not contain invalid characters: ASCII Control characters (0-31;127), space, tab and the following characters: ()<>@,;:\"/?={}
*/
public function testThrowsExceptionWithStrictMode()
{
$a = new CookieJar(true);
$a->setCookie(new SetCookie(['Name' => "abc\n", 'Value' => 'foo', 'Domain' => 'bar']));
}
public function testDeletesCookiesByName()
{
$cookies = $this->getTestCookies();
$cookies[] = new SetCookie([
'Name' => 'other',
'Value' => '123',
'Domain' => 'bar.com',
'Path' => '/boo',
'Expires' => time() + 1000
]);
$jar = new CookieJar();
foreach ($cookies as $cookie) {
$jar->setCookie($cookie);
}
self::assertCount(4, $jar);
$jar->clear('bar.com', '/boo', 'other');
self::assertCount(3, $jar);
$names = array_map(function (SetCookie $c) {
return $c->getName();
}, $jar->getIterator()->getArrayCopy());
self::assertSame(['foo', 'test', 'you'], $names);
}
public function testCanConvertToAndLoadFromArray()
{
$jar = new CookieJar(true);
foreach ($this->getTestCookies() as $cookie) {
$jar->setCookie($cookie);
}
self::assertCount(3, $jar);
$arr = $jar->toArray();
self::assertCount(3, $arr);
$newCookieJar = new CookieJar(false, $arr);
self::assertCount(3, $newCookieJar);
self::assertSame($jar->toArray(), $newCookieJar->toArray());
}
public function testAddsCookiesWithEmptyPathFromResponse()
{
$response = new Response(200, [
'Set-Cookie' => "fpc=foobar; expires={$this->futureExpirationDate()}; path=;"
]);
$request = new Request('GET', 'http://www.example.com');
$this->jar->extractCookies($request, $response);
$newRequest = $this->jar->withCookieHeader(new Request('GET', 'http://www.example.com/foo'));
self::assertTrue($newRequest->hasHeader('Cookie'));
}
public function getCookiePathsDataProvider()
{
return [
['', '/'],
['/', '/'],
['/foo', '/'],
['/foo/bar', '/foo'],
['/foo/bar/', '/foo/bar'],
];
}
/**
* @dataProvider getCookiePathsDataProvider
*/
public function testCookiePathWithEmptySetCookiePath($uriPath, $cookiePath)
{
$response = (new Response(200))
->withAddedHeader(
'Set-Cookie',
"foo=bar; expires={$this->futureExpirationDate()}; domain=www.example.com; path=;"
)
->withAddedHeader(
'Set-Cookie',
"bar=foo; expires={$this->futureExpirationDate()}; domain=www.example.com; path=foobar;"
)
;
$request = (new Request('GET', "https://www.example.com{$uriPath}"));
$this->jar->extractCookies($request, $response);
self::assertSame($cookiePath, $this->jar->toArray()[0]['Path']);
self::assertSame($cookiePath, $this->jar->toArray()[1]['Path']);
}
public function getDomainMatchesProvider()
{
return [
['www.example.com', 'www.example.com', true],
['www.example.com', 'www.EXAMPLE.com', true],
['www.example.com', 'www.example.net', false],
['www.example.com', 'ftp.example.com', false],
['www.example.com', 'example.com', true],
['www.example.com', 'EXAMPLE.com', true],
['fra.de.example.com', 'EXAMPLE.com', true],
['www.EXAMPLE.com', 'www.example.com', true],
['www.EXAMPLE.com', 'www.example.COM', true],
];
}
/**
* @dataProvider getDomainMatchesProvider
*/
public function testIgnoresCookiesForMismatchingDomains($requestHost, $domainAttribute, $matches)
{
$response = (new Response(200))
->withAddedHeader(
'Set-Cookie',
"foo=bar; expires={$this->futureExpirationDate()}; domain={$domainAttribute}; path=/;"
)
;
$request = (new Request('GET', "https://{$requestHost}/"));
$this->jar->extractCookies($request, $response);
self::assertCount($matches ? 1 : 0, $this->jar->toArray());
}
private function futureExpirationDate()
{
return (new DateTimeImmutable)->add(new DateInterval('P1D'))->format(DateTime::COOKIE);
}
}

View File

@ -0,0 +1,88 @@
<?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\FileCookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\Cookie\FileCookieJar
*/
class FileCookieJarTest extends TestCase
{
private $file;
public function setUp()
{
$this->file = tempnam('/tmp', 'file-cookies');
}
/**
* @expectedException \RuntimeException
*/
public function testValidatesCookieFile()
{
file_put_contents($this->file, 'true');
new FileCookieJar($this->file);
}
public function testLoadsFromFile()
{
$jar = new FileCookieJar($this->file);
self::assertSame([], $jar->getIterator()->getArrayCopy());
unlink($this->file);
}
/**
* @dataProvider providerPersistsToFileFileParameters
*/
public function testPersistsToFile($testSaveSessionCookie = false)
{
$jar = new FileCookieJar($this->file, $testSaveSessionCookie);
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => time() + 1000
]));
$jar->setCookie(new SetCookie([
'Name' => 'baz',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => time() + 1000
]));
$jar->setCookie(new SetCookie([
'Name' => 'boo',
'Value' => 'bar',
'Domain' => 'foo.com',
]));
self::assertCount(3, $jar);
unset($jar);
// Make sure it wrote to the file
$contents = file_get_contents($this->file);
self::assertNotEmpty($contents);
// Load the cookieJar from the file
$jar = new FileCookieJar($this->file);
if ($testSaveSessionCookie) {
self::assertCount(3, $jar);
} else {
// Weeds out temporary and session cookies
self::assertCount(2, $jar);
}
unset($jar);
unlink($this->file);
}
public function providerPersistsToFileFileParameters()
{
return [
[false],
[true]
];
}
}

View File

@ -0,0 +1,92 @@
<?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\SessionCookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\Cookie\SessionCookieJar
*/
class SessionCookieJarTest extends TestCase
{
private $sessionVar;
public function setUp()
{
$this->sessionVar = 'sessionKey';
if (!isset($_SESSION)) {
$_SESSION = [];
}
}
/**
* @expectedException \RuntimeException
*/
public function testValidatesCookieSession()
{
$_SESSION[$this->sessionVar] = 'true';
new SessionCookieJar($this->sessionVar);
}
public function testLoadsFromSession()
{
$jar = new SessionCookieJar($this->sessionVar);
self::assertSame([], $jar->getIterator()->getArrayCopy());
unset($_SESSION[$this->sessionVar]);
}
/**
* @dataProvider providerPersistsToSessionParameters
*/
public function testPersistsToSession($testSaveSessionCookie = false)
{
$jar = new SessionCookieJar($this->sessionVar, $testSaveSessionCookie);
$jar->setCookie(new SetCookie([
'Name' => 'foo',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => time() + 1000
]));
$jar->setCookie(new SetCookie([
'Name' => 'baz',
'Value' => 'bar',
'Domain' => 'foo.com',
'Expires' => time() + 1000
]));
$jar->setCookie(new SetCookie([
'Name' => 'boo',
'Value' => 'bar',
'Domain' => 'foo.com',
]));
self::assertCount(3, $jar);
unset($jar);
// Make sure it wrote to the sessionVar in $_SESSION
$contents = $_SESSION[$this->sessionVar];
self::assertNotEmpty($contents);
// Load the cookieJar from the file
$jar = new SessionCookieJar($this->sessionVar);
if ($testSaveSessionCookie) {
self::assertCount(3, $jar);
} else {
// Weeds out temporary and session cookies
self::assertCount(2, $jar);
}
unset($jar);
unset($_SESSION[$this->sessionVar]);
}
public function providerPersistsToSessionParameters()
{
return [
[false],
[true]
];
}
}

View File

@ -0,0 +1,445 @@
<?php
namespace GuzzleHttp\Tests\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\Cookie\SetCookie
*/
class SetCookieTest extends TestCase
{
public function testInitializesDefaultValues()
{
$cookie = new SetCookie();
self::assertSame('/', $cookie->getPath());
}
public function testConvertsDateTimeMaxAgeToUnixTimestamp()
{
$cookie = new SetCookie(['Expires' => 'November 20, 1984']);
self::assertInternalType('integer', $cookie->getExpires());
}
public function testAddsExpiresBasedOnMaxAge()
{
$t = time();
$cookie = new SetCookie(['Max-Age' => 100]);
self::assertEquals($t + 100, $cookie->getExpires());
}
public function testHoldsValues()
{
$t = time();
$data = [
'Name' => 'foo',
'Value' => 'baz',
'Path' => '/bar',
'Domain' => 'baz.com',
'Expires' => $t,
'Max-Age' => 100,
'Secure' => true,
'Discard' => true,
'HttpOnly' => true,
'foo' => 'baz',
'bar' => 'bam'
];
$cookie = new SetCookie($data);
self::assertEquals($data, $cookie->toArray());
self::assertSame('foo', $cookie->getName());
self::assertSame('baz', $cookie->getValue());
self::assertSame('baz.com', $cookie->getDomain());
self::assertSame('/bar', $cookie->getPath());
self::assertSame($t, $cookie->getExpires());
self::assertSame(100, $cookie->getMaxAge());
self::assertTrue($cookie->getSecure());
self::assertTrue($cookie->getDiscard());
self::assertTrue($cookie->getHttpOnly());
self::assertSame('baz', $cookie->toArray()['foo']);
self::assertSame('bam', $cookie->toArray()['bar']);
$cookie->setName('a');
$cookie->setValue('b');
$cookie->setPath('c');
$cookie->setDomain('bar.com');
$cookie->setExpires(10);
$cookie->setMaxAge(200);
$cookie->setSecure(false);
$cookie->setHttpOnly(false);
$cookie->setDiscard(false);
self::assertSame('a', $cookie->getName());
self::assertSame('b', $cookie->getValue());
self::assertSame('c', $cookie->getPath());
self::assertSame('bar.com', $cookie->getDomain());
self::assertSame(10, $cookie->getExpires());
self::assertSame(200, $cookie->getMaxAge());
self::assertFalse($cookie->getSecure());
self::assertFalse($cookie->getDiscard());
self::assertFalse($cookie->getHttpOnly());
}
public function testDeterminesIfExpired()
{
$c = new SetCookie();
$c->setExpires(10);
self::assertTrue($c->isExpired());
$c->setExpires(time() + 10000);
self::assertFalse($c->isExpired());
}
public function testMatchesDomain()
{
$cookie = new SetCookie();
self::assertTrue($cookie->matchesDomain('baz.com'));
$cookie->setDomain('baz.com');
self::assertTrue($cookie->matchesDomain('baz.com'));
self::assertFalse($cookie->matchesDomain('bar.com'));
$cookie->setDomain('.baz.com');
self::assertTrue($cookie->matchesDomain('.baz.com'));
self::assertTrue($cookie->matchesDomain('foo.baz.com'));
self::assertFalse($cookie->matchesDomain('baz.bar.com'));
self::assertTrue($cookie->matchesDomain('baz.com'));
$cookie->setDomain('.127.0.0.1');
self::assertTrue($cookie->matchesDomain('127.0.0.1'));
$cookie->setDomain('127.0.0.1');
self::assertTrue($cookie->matchesDomain('127.0.0.1'));
$cookie->setDomain('.com.');
self::assertFalse($cookie->matchesDomain('baz.com'));
$cookie->setDomain('.local');
self::assertTrue($cookie->matchesDomain('example.local'));
$cookie->setDomain('example.com/'); // malformed domain
self::assertFalse($cookie->matchesDomain('example.com'));
}
public function pathMatchProvider()
{
return [
['/foo', '/foo', true],
['/foo', '/Foo', false],
['/foo', '/fo', false],
['/foo', '/foo/bar', true],
['/foo', '/foo/bar/baz', true],
['/foo', '/foo/bar//baz', true],
['/foo', '/foobar', false],
['/foo/bar', '/foo', false],
['/foo/bar', '/foobar', false],
['/foo/bar', '/foo/bar', true],
['/foo/bar', '/foo/bar/', true],
['/foo/bar', '/foo/bar/baz', true],
['/foo/bar/', '/foo/bar', false],
['/foo/bar/', '/foo/bar/', true],
['/foo/bar/', '/foo/bar/baz', true],
];
}
/**
* @dataProvider pathMatchProvider
*/
public function testMatchesPath($cookiePath, $requestPath, $isMatch)
{
$cookie = new SetCookie();
$cookie->setPath($cookiePath);
self::assertSame($isMatch, $cookie->matchesPath($requestPath));
}
public function cookieValidateProvider()
{
return [
['foo', 'baz', 'bar', true],
['0', '0', '0', true],
['foo[bar]', 'baz', 'bar', true],
['', 'baz', 'bar', 'The cookie name must not be empty'],
['foo', '', 'bar', 'The cookie value must not be empty'],
['foo', 'baz', '', 'The cookie domain must not be empty'],
["foo\r", 'baz', '0', 'Cookie name must not contain invalid characters: ASCII Control characters (0-31;127), space, tab and the following characters: ()<>@,;:\"/?={}'],
];
}
/**
* @dataProvider cookieValidateProvider
*/
public function testValidatesCookies($name, $value, $domain, $result)
{
$cookie = new SetCookie([
'Name' => $name,
'Value' => $value,
'Domain' => $domain,
]);
self::assertSame($result, $cookie->validate());
}
public function testDoesNotMatchIp()
{
$cookie = new SetCookie(['Domain' => '192.168.16.']);
self::assertFalse($cookie->matchesDomain('192.168.16.121'));
}
public function testConvertsToString()
{
$t = 1382916008;
$cookie = new SetCookie([
'Name' => 'test',
'Value' => '123',
'Domain' => 'foo.com',
'Expires' => $t,
'Path' => '/abc',
'HttpOnly' => true,
'Secure' => true
]);
self::assertSame(
'test=123; Domain=foo.com; Path=/abc; Expires=Sun, 27 Oct 2013 23:20:08 GMT; Secure; HttpOnly',
(string) $cookie
);
}
/**
* Provides the parsed information from a cookie
*
* @return array
*/
public function cookieParserDataProvider()
{
return [
[
'ASIHTTPRequestTestCookie=This+is+the+value; expires=Sat, 26-Jul-2008 17:00:42 GMT; path=/tests; domain=allseeing-i.com; PHPSESSID=6c951590e7a9359bcedde25cda73e43c; path=/;',
[
'Domain' => 'allseeing-i.com',
'Path' => '/',
'PHPSESSID' => '6c951590e7a9359bcedde25cda73e43c',
'Max-Age' => null,
'Expires' => 'Sat, 26-Jul-2008 17:00:42 GMT',
'Secure' => null,
'Discard' => null,
'Name' => 'ASIHTTPRequestTestCookie',
'Value' => 'This+is+the+value',
'HttpOnly' => false
]
],
['', []],
['foo', []],
['; foo', []],
[
'foo="bar"',
[
'Name' => 'foo',
'Value' => '"bar"',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false
]
],
// Test setting a blank value for a cookie
[[
'foo=', 'foo =', 'foo =;', 'foo= ;', 'foo =', 'foo= '],
[
'Name' => 'foo',
'Value' => '',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false
]
],
// Test setting a value and removing quotes
[[
'foo=1', 'foo =1', 'foo =1;', 'foo=1 ;', 'foo =1', 'foo= 1', 'foo = 1 ;'],
[
'Name' => 'foo',
'Value' => '1',
'Discard' => null,
'Domain' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false
]
],
// Some of the following tests are based on http://framework.zend.com/svn/framework/standard/trunk/tests/Zend/Http/CookieTest.php
[
'justacookie=foo; domain=example.com',
[
'Name' => 'justacookie',
'Value' => 'foo',
'Domain' => 'example.com',
'Discard' => null,
'Expires' => null,
'Max-Age' => null,
'Path' => '/',
'Secure' => null,
'HttpOnly' => false
]
],
[
'expires=tomorrow; secure; path=/Space Out/; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=.example.com',
[
'Name' => 'expires',
'Value' => 'tomorrow',
'Domain' => '.example.com',
'Path' => '/Space Out/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Discard' => null,
'Secure' => true,
'Max-Age' => null,
'HttpOnly' => false
]
],
[
'domain=unittests; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=example.com; path=/some value/',
[
'Name' => 'domain',
'Value' => 'unittests',
'Domain' => 'example.com',
'Path' => '/some value/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => false,
'Discard' => null,
'Max-Age' => null,
'HttpOnly' => false
]
],
[
'path=indexAction; path=/; domain=.foo.com; expires=Tue, 21-Nov-2006 08:33:44 GMT',
[
'Name' => 'path',
'Value' => 'indexAction',
'Domain' => '.foo.com',
'Path' => '/',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => false,
'Discard' => null,
'Max-Age' => null,
'HttpOnly' => false
]
],
[
'secure=sha1; secure; SECURE; domain=some.really.deep.domain.com; version=1; Max-Age=86400',
[
'Name' => 'secure',
'Value' => 'sha1',
'Domain' => 'some.really.deep.domain.com',
'Path' => '/',
'Secure' => true,
'Discard' => null,
'Expires' => time() + 86400,
'Max-Age' => 86400,
'HttpOnly' => false,
'version' => '1'
]
],
[
'PHPSESSID=123456789+abcd%2Cef; secure; discard; domain=.localdomain; path=/foo/baz; expires=Tue, 21-Nov-2006 08:33:44 GMT;',
[
'Name' => 'PHPSESSID',
'Value' => '123456789+abcd%2Cef',
'Domain' => '.localdomain',
'Path' => '/foo/baz',
'Expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'Secure' => true,
'Discard' => true,
'Max-Age' => null,
'HttpOnly' => false
]
],
];
}
/**
* @dataProvider cookieParserDataProvider
*/
public function testParseCookie($cookie, $parsed)
{
foreach ((array) $cookie as $v) {
$c = SetCookie::fromString($v);
$p = $c->toArray();
if (isset($p['Expires'])) {
// Remove expires values from the assertion if they are relatively equal
if (abs($p['Expires'] != strtotime($parsed['Expires'])) < 40) {
unset($p['Expires']);
unset($parsed['Expires']);
}
}
if (!empty($parsed)) {
foreach ($parsed as $key => $value) {
self::assertEquals($parsed[$key], $p[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true));
}
foreach ($p as $key => $value) {
self::assertEquals($p[$key], $parsed[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true));
}
} else {
self::assertSame([
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
], $p);
}
}
}
/**
* Provides the data for testing isExpired
*
* @return array
*/
public function isExpiredProvider()
{
return [
[
'FOO=bar; expires=Thu, 01 Jan 1970 00:00:00 GMT;',
true,
],
[
'FOO=bar; expires=Thu, 01 Jan 1970 00:00:01 GMT;',
true,
],
[
'FOO=bar; expires=' . date(\DateTime::RFC1123, time()+10) . ';',
false,
],
[
'FOO=bar; expires=' . date(\DateTime::RFC1123, time()-10) . ';',
true,
],
[
'FOO=bar;',
false,
],
];
}
/**
* @dataProvider isExpiredProvider
*/
public function testIsExpired($cookie, $expired)
{
self::assertSame(
$expired,
SetCookie::fromString($cookie)->isExpired()
);
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Exception\ConnectException
*/
class ConnectExceptionTest extends TestCase
{
public function testHasNoResponse()
{
$req = new Request('GET', '/');
$prev = new \Exception();
$e = new ConnectException('foo', $req, $prev, ['foo' => 'bar']);
self::assertSame($req, $e->getRequest());
self::assertNull($e->getResponse());
self::assertFalse($e->hasResponse());
self::assertSame('foo', $e->getMessage());
self::assertSame('bar', $e->getHandlerContext()['foo']);
self::assertSame($prev, $e->getPrevious());
}
}

View File

@ -0,0 +1,195 @@
<?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Stream;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Exception\RequestException
*/
class RequestExceptionTest extends TestCase
{
public function testHasRequestAndResponse()
{
$req = new Request('GET', '/');
$res = new Response(200);
$e = new RequestException('foo', $req, $res);
self::assertSame($req, $e->getRequest());
self::assertSame($res, $e->getResponse());
self::assertTrue($e->hasResponse());
self::assertSame('foo', $e->getMessage());
}
public function testCreatesGenerateException()
{
$e = RequestException::create(new Request('GET', '/'));
self::assertSame('Error completing request', $e->getMessage());
self::assertInstanceOf('GuzzleHttp\Exception\RequestException', $e);
}
public function testCreatesClientErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(400));
self::assertContains(
'GET /',
$e->getMessage()
);
self::assertContains(
'400 Bad Request',
$e->getMessage()
);
self::assertInstanceOf('GuzzleHttp\Exception\ClientException', $e);
}
public function testCreatesServerErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(500));
self::assertContains(
'GET /',
$e->getMessage()
);
self::assertContains(
'500 Internal Server Error',
$e->getMessage()
);
self::assertInstanceOf('GuzzleHttp\Exception\ServerException', $e);
}
public function testCreatesGenericErrorResponseException()
{
$e = RequestException::create(new Request('GET', '/'), new Response(300));
self::assertContains(
'GET /',
$e->getMessage()
);
self::assertContains(
'300 ',
$e->getMessage()
);
self::assertInstanceOf('GuzzleHttp\Exception\RequestException', $e);
}
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Status code must be an integer value between 1xx and 5xx.
*/
public function testThrowsInvalidArgumentExceptionOnOutOfBoundsResponseCode()
{
throw RequestException::create(new Request('GET', '/'), new Response(600));
}
public function dataPrintableResponses()
{
return [
['You broke the test!'],
['<h1>zlomený zkouška</h1>'],
['{"tester": "Philépe Gonzalez"}'],
["<xml>\n\t<text>Your friendly test</text>\n</xml>"],
['document.body.write("here comes a test");'],
["body:before {\n\tcontent: 'test style';\n}"],
];
}
/**
* @dataProvider dataPrintableResponses
*/
public function testCreatesExceptionWithPrintableBodySummary($content)
{
$response = new Response(
500,
[],
$content
);
$e = RequestException::create(new Request('GET', '/'), $response);
self::assertContains(
$content,
$e->getMessage()
);
self::assertInstanceOf('GuzzleHttp\Exception\RequestException', $e);
}
public function testCreatesExceptionWithTruncatedSummary()
{
$content = str_repeat('+', 121);
$response = new Response(500, [], $content);
$e = RequestException::create(new Request('GET', '/'), $response);
$expected = str_repeat('+', 120) . ' (truncated...)';
self::assertContains($expected, $e->getMessage());
}
public function testExceptionMessageIgnoresEmptyBody()
{
$e = RequestException::create(new Request('GET', '/'), new Response(500));
self::assertStringEndsWith('response', $e->getMessage());
}
public function testHasStatusCodeAsExceptionCode()
{
$e = RequestException::create(new Request('GET', '/'), new Response(442));
self::assertSame(442, $e->getCode());
}
public function testWrapsRequestExceptions()
{
$e = new \Exception('foo');
$r = new Request('GET', 'http://www.oo.com');
$ex = RequestException::wrapException($r, $e);
self::assertInstanceOf('GuzzleHttp\Exception\RequestException', $ex);
self::assertSame($e, $ex->getPrevious());
}
public function testDoesNotWrapExistingRequestExceptions()
{
$r = new Request('GET', 'http://www.oo.com');
$e = new RequestException('foo', $r);
$e2 = RequestException::wrapException($r, $e);
self::assertSame($e, $e2);
}
public function testCanProvideHandlerContext()
{
$r = new Request('GET', 'http://www.oo.com');
$e = new RequestException('foo', $r, null, null, ['bar' => 'baz']);
self::assertSame(['bar' => 'baz'], $e->getHandlerContext());
}
public function testObfuscateUrlWithUsername()
{
$r = new Request('GET', 'http://username@www.oo.com');
$e = RequestException::create($r, new Response(500));
self::assertContains('http://username@www.oo.com', $e->getMessage());
}
public function testObfuscateUrlWithUsernameAndPassword()
{
$r = new Request('GET', 'http://user:password@www.oo.com');
$e = RequestException::create($r, new Response(500));
self::assertContains('http://user:***@www.oo.com', $e->getMessage());
}
public function testGetResponseBodySummaryOfNonReadableStream()
{
self::assertNull(RequestException::getResponseBodySummary(new Response(500, [], new ReadSeekOnlyStream())));
}
}
final class ReadSeekOnlyStream extends Stream
{
public function __construct()
{
parent::__construct(fopen('php://memory', 'wb'));
}
public function isSeekable()
{
return true;
}
public function isReadable()
{
return false;
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace GuzzleHttp\Tests\Exception;
use GuzzleHttp\Exception\SeekException;
use GuzzleHttp\Psr7;
use PHPUnit\Framework\TestCase;
class SeekExceptionTest extends TestCase
{
public function testHasStream()
{
$s = Psr7\stream_for('foo');
$e = new SeekException($s, 10);
self::assertSame($s, $e->getStream());
self::assertContains('10', $e->getMessage());
}
}

View File

@ -0,0 +1,770 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler;
use GuzzleHttp\Handler\CurlFactory;
use GuzzleHttp\Handler\EasyHandle;
use GuzzleHttp\Psr7;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
/**
* @covers \GuzzleHttp\Handler\CurlFactory
*/
class CurlFactoryTest extends TestCase
{
public static function setUpBeforeClass()
{
$_SERVER['curl_test'] = true;
unset($_SERVER['_curl']);
}
public static function tearDownAfterClass()
{
unset($_SERVER['_curl'], $_SERVER['curl_test']);
}
public function testCreatesCurlHandle()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, [
'Foo' => 'Bar',
'Baz' => 'bam',
'Content-Length' => 2,
], 'hi')
]);
$stream = Psr7\stream_for();
$request = new Psr7\Request('PUT', Server::$url, [
'Hi' => ' 123',
'Content-Length' => '7'
], 'testing');
$f = new Handler\CurlFactory(3);
$result = $f->create($request, ['sink' => $stream]);
self::assertInstanceOf(EasyHandle::class, $result);
self::assertInternalType('resource', $result->handle);
self::assertInternalType('array', $result->headers);
self::assertSame($stream, $result->sink);
curl_close($result->handle);
self::assertSame('PUT', $_SERVER['_curl'][CURLOPT_CUSTOMREQUEST]);
self::assertSame(
'http://127.0.0.1:8126/',
$_SERVER['_curl'][CURLOPT_URL]
);
// Sends via post fields when the request is small enough
self::assertSame('testing', $_SERVER['_curl'][CURLOPT_POSTFIELDS]);
self::assertEquals(0, $_SERVER['_curl'][CURLOPT_RETURNTRANSFER]);
self::assertEquals(0, $_SERVER['_curl'][CURLOPT_HEADER]);
self::assertSame(150, $_SERVER['_curl'][CURLOPT_CONNECTTIMEOUT]);
self::assertInstanceOf('Closure', $_SERVER['_curl'][CURLOPT_HEADERFUNCTION]);
if (defined('CURLOPT_PROTOCOLS')) {
self::assertSame(
CURLPROTO_HTTP | CURLPROTO_HTTPS,
$_SERVER['_curl'][CURLOPT_PROTOCOLS]
);
}
self::assertContains('Expect:', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
self::assertContains('Accept:', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
self::assertContains('Content-Type:', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
self::assertContains('Hi: 123', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
self::assertContains('Host: 127.0.0.1:8126', $_SERVER['_curl'][CURLOPT_HTTPHEADER]);
}
public function testSendsHeadRequests()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$response = $a(new Psr7\Request('HEAD', Server::$url), []);
$response->wait();
self::assertEquals(true, $_SERVER['_curl'][CURLOPT_NOBODY]);
$checks = [CURLOPT_WRITEFUNCTION, CURLOPT_READFUNCTION, CURLOPT_INFILE];
foreach ($checks as $check) {
self::assertArrayNotHasKey($check, $_SERVER['_curl']);
}
self::assertEquals('HEAD', Server::received()[0]->getMethod());
}
public function testCanAddCustomCurlOptions()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$req = new Psr7\Request('GET', Server::$url);
$a($req, ['curl' => [CURLOPT_LOW_SPEED_LIMIT => 10]]);
self::assertEquals(10, $_SERVER['_curl'][CURLOPT_LOW_SPEED_LIMIT]);
}
public function testCanChangeCurlOptions()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$req = new Psr7\Request('GET', Server::$url);
$a($req, ['curl' => [CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0]]);
self::assertEquals(CURL_HTTP_VERSION_1_0, $_SERVER['_curl'][CURLOPT_HTTP_VERSION]);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage SSL CA bundle not found: /does/not/exist
*/
public function testValidatesVerify()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => '/does/not/exist']);
}
public function testCanSetVerifyToFile()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', 'http://foo.com'), ['verify' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_CAINFO]);
self::assertEquals(2, $_SERVER['_curl'][CURLOPT_SSL_VERIFYHOST]);
self::assertEquals(true, $_SERVER['_curl'][CURLOPT_SSL_VERIFYPEER]);
}
public function testCanSetVerifyToDir()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', 'http://foo.com'), ['verify' => __DIR__]);
self::assertEquals(__DIR__, $_SERVER['_curl'][CURLOPT_CAPATH]);
self::assertEquals(2, $_SERVER['_curl'][CURLOPT_SSL_VERIFYHOST]);
self::assertEquals(true, $_SERVER['_curl'][CURLOPT_SSL_VERIFYPEER]);
}
public function testAddsVerifyAsTrue()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => true]);
self::assertEquals(2, $_SERVER['_curl'][CURLOPT_SSL_VERIFYHOST]);
self::assertEquals(true, $_SERVER['_curl'][CURLOPT_SSL_VERIFYPEER]);
self::assertArrayNotHasKey(CURLOPT_CAINFO, $_SERVER['_curl']);
}
public function testCanDisableVerify()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['verify' => false]);
self::assertEquals(0, $_SERVER['_curl'][CURLOPT_SSL_VERIFYHOST]);
self::assertEquals(false, $_SERVER['_curl'][CURLOPT_SSL_VERIFYPEER]);
}
public function testAddsProxy()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['proxy' => 'http://bar.com']);
self::assertEquals('http://bar.com', $_SERVER['_curl'][CURLOPT_PROXY]);
}
public function testAddsViaScheme()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), [
'proxy' => ['http' => 'http://bar.com', 'https' => 'https://t'],
]);
self::assertEquals('http://bar.com', $_SERVER['_curl'][CURLOPT_PROXY]);
$this->checkNoProxyForHost('http://test.test.com', ['test.test.com'], false);
$this->checkNoProxyForHost('http://test.test.com', ['.test.com'], false);
$this->checkNoProxyForHost('http://test.test.com', ['*.test.com'], true);
$this->checkNoProxyForHost('http://test.test.com', ['*'], false);
$this->checkNoProxyForHost('http://127.0.0.1', ['127.0.0.*'], true);
}
private function checkNoProxyForHost($url, $noProxy, $assertUseProxy)
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', $url), [
'proxy' => [
'http' => 'http://bar.com',
'https' => 'https://t',
'no' => $noProxy
],
]);
if ($assertUseProxy) {
self::assertArrayHasKey(CURLOPT_PROXY, $_SERVER['_curl']);
} else {
self::assertArrayNotHasKey(CURLOPT_PROXY, $_SERVER['_curl']);
}
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage SSL private key not found: /does/not/exist
*/
public function testValidatesSslKey()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => '/does/not/exist']);
}
public function testAddsSslKey()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLKEY]);
}
public function testAddsSslKeyWithPassword()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => [__FILE__, 'test']]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLKEY]);
self::assertEquals('test', $_SERVER['_curl'][CURLOPT_SSLKEYPASSWD]);
}
public function testAddsSslKeyWhenUsingArraySyntaxButNoPassword()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['ssl_key' => [__FILE__]]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLKEY]);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage SSL certificate not found: /does/not/exist
*/
public function testValidatesCert()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => '/does/not/exist']);
}
public function testAddsCert()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => __FILE__]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLCERT]);
}
public function testAddsCertWithPassword()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['cert' => [__FILE__, 'test']]);
self::assertEquals(__FILE__, $_SERVER['_curl'][CURLOPT_SSLCERT]);
self::assertEquals('test', $_SERVER['_curl'][CURLOPT_SSLCERTPASSWD]);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage progress client option must be callable
*/
public function testValidatesProgress()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), ['progress' => 'foo']);
}
public function testEmitsDebugInfoToStream()
{
$res = fopen('php://memory', 'r+');
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$response = $a(new Psr7\Request('HEAD', Server::$url), ['debug' => $res]);
$response->wait();
rewind($res);
$output = str_replace("\r", '', stream_get_contents($res));
self::assertContains("> HEAD / HTTP/1.1", $output);
self::assertContains("< HTTP/1.1 200", $output);
fclose($res);
}
public function testEmitsProgressToFunction()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$called = [];
$request = new Psr7\Request('HEAD', Server::$url);
$response = $a($request, [
'progress' => function () use (&$called) {
$called[] = func_get_args();
},
]);
$response->wait();
self::assertNotEmpty($called);
foreach ($called as $call) {
self::assertCount(4, $call);
}
}
private function addDecodeResponse($withEncoding = true)
{
$content = gzencode('test');
$headers = ['Content-Length' => strlen($content)];
if ($withEncoding) {
$headers['Content-Encoding'] = 'gzip';
}
$response = new Psr7\Response(200, $headers, $content);
Server::flush();
Server::enqueue([$response]);
return $content;
}
public function testDecodesGzippedResponses()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertEquals('test', (string) $response->getBody());
self::assertEquals('', $_SERVER['_curl'][CURLOPT_ENCODING]);
$sent = Server::received()[0];
self::assertFalse($sent->hasHeader('Accept-Encoding'));
}
public function testReportsOriginalSizeAndContentEncodingAfterDecoding()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertSame(
'gzip',
$response->getHeaderLine('x-encoded-content-encoding')
);
self::assertSame(
strlen(gzencode('test')),
(int) $response->getHeaderLine('x-encoded-content-length')
);
}
public function testDecodesGzippedResponsesWithHeader()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url, ['Accept-Encoding' => 'gzip']);
$response = $handler($request, ['decode_content' => true]);
$response = $response->wait();
self::assertEquals('gzip', $_SERVER['_curl'][CURLOPT_ENCODING]);
$sent = Server::received()[0];
self::assertEquals('gzip', $sent->getHeaderLine('Accept-Encoding'));
self::assertEquals('test', (string) $response->getBody());
self::assertFalse($response->hasHeader('content-encoding'));
self::assertTrue(
!$response->hasHeader('content-length') ||
$response->getHeaderLine('content-length') == $response->getBody()->getSize()
);
}
public function testDoesNotForceDecode()
{
$content = $this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => false]);
$response = $response->wait();
$sent = Server::received()[0];
self::assertFalse($sent->hasHeader('Accept-Encoding'));
self::assertEquals($content, (string) $response->getBody());
}
public function testProtocolVersion()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$a = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url, [], null, '1.0');
$a($request, []);
self::assertEquals(CURL_HTTP_VERSION_1_0, $_SERVER['_curl'][CURLOPT_HTTP_VERSION]);
}
public function testSavesToStream()
{
$stream = fopen('php://memory', 'r+');
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $stream,
]);
$response->wait();
rewind($stream);
self::assertEquals('test', stream_get_contents($stream));
}
public function testSavesToGuzzleStream()
{
$stream = Psr7\stream_for();
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $stream,
]);
$response->wait();
self::assertEquals('test', (string) $stream);
}
public function testSavesToFileOnDisk()
{
$tmpfile = tempnam(sys_get_temp_dir(), 'testfile');
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('GET', Server::$url);
$response = $handler($request, [
'decode_content' => true,
'sink' => $tmpfile,
]);
$response->wait();
self::assertStringEqualsFile($tmpfile, 'test');
unlink($tmpfile);
}
public function testDoesNotAddMultipleContentLengthHeaders()
{
$this->addDecodeResponse();
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('PUT', Server::$url, ['Content-Length' => 3], 'foo');
$response = $handler($request, []);
$response->wait();
$sent = Server::received()[0];
self::assertEquals(3, $sent->getHeaderLine('Content-Length'));
self::assertFalse($sent->hasHeader('Transfer-Encoding'));
self::assertEquals('foo', (string) $sent->getBody());
}
public function testSendsPostWithNoBodyOrDefaultContentType()
{
Server::flush();
Server::enqueue([new Psr7\Response()]);
$handler = new Handler\CurlMultiHandler();
$request = new Psr7\Request('POST', Server::$url);
$response = $handler($request, []);
$response->wait();
$received = Server::received()[0];
self::assertEquals('POST', $received->getMethod());
self::assertFalse($received->hasHeader('content-type'));
self::assertSame('0', $received->getHeaderLine('content-length'));
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage but attempting to rewind the request body failed
*/
public function testFailsWhenCannotRewindRetryAfterNoResponse()
{
$factory = new Handler\CurlFactory(1);
$stream = Psr7\stream_for('abc');
$stream->read(1);
$stream = new Psr7\NoSeekStream($stream);
$request = new Psr7\Request('PUT', Server::$url, [], $stream);
$fn = function ($request, $options) use (&$fn, $factory) {
$easy = $factory->create($request, $options);
return Handler\CurlFactory::finish($fn, $easy, $factory);
};
$fn($request, [])->wait();
}
public function testRetriesWhenBodyCanBeRewound()
{
$callHandler = $called = false;
$fn = function ($r, $options) use (&$callHandler) {
$callHandler = true;
return \GuzzleHttp\Promise\promise_for(new Psr7\Response());
};
$bd = Psr7\FnStream::decorate(Psr7\stream_for('test'), [
'tell' => function () {
return 1;
},
'rewind' => function () use (&$called) {
$called = true;
}
]);
$factory = new Handler\CurlFactory(1);
$req = new Psr7\Request('PUT', Server::$url, [], $bd);
$easy = $factory->create($req, []);
$res = Handler\CurlFactory::finish($fn, $easy, $factory);
$res = $res->wait();
self::assertTrue($callHandler);
self::assertTrue($called);
self::assertEquals('200', $res->getStatusCode());
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage The cURL request was retried 3 times
*/
public function testFailsWhenRetryMoreThanThreeTimes()
{
$factory = new Handler\CurlFactory(1);
$call = 0;
$fn = function ($request, $options) use (&$mock, &$call, $factory) {
$call++;
$easy = $factory->create($request, $options);
return Handler\CurlFactory::finish($mock, $easy, $factory);
};
$mock = new Handler\MockHandler([$fn, $fn, $fn]);
$p = $mock(new Psr7\Request('PUT', Server::$url, [], 'test'), []);
$p->wait(false);
self::assertEquals(3, $call);
$p->wait(true);
}
public function testHandles100Continue()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['Test' => 'Hello', 'Content-Length' => 4], 'test'),
]);
$request = new Psr7\Request('PUT', Server::$url, [
'Expect' => '100-Continue'
], 'test');
$handler = new Handler\CurlMultiHandler();
$response = $handler($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('Hello', $response->getHeaderLine('Test'));
self::assertSame('4', $response->getHeaderLine('Content-Length'));
self::assertSame('test', (string) $response->getBody());
}
/**
* @expectedException \GuzzleHttp\Exception\ConnectException
*/
public function testCreatesConnectException()
{
$m = new \ReflectionMethod(CurlFactory::class, 'finishError');
$m->setAccessible(true);
$factory = new Handler\CurlFactory(1);
$easy = $factory->create(new Psr7\Request('GET', Server::$url), []);
$easy->errno = CURLE_COULDNT_CONNECT;
$response = $m->invoke(
null,
function () {
},
$easy,
$factory
);
$response->wait();
}
public function testAddsTimeouts()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), [
'timeout' => 0.1,
'connect_timeout' => 0.2
]);
self::assertEquals(100, $_SERVER['_curl'][CURLOPT_TIMEOUT_MS]);
self::assertEquals(200, $_SERVER['_curl'][CURLOPT_CONNECTTIMEOUT_MS]);
}
public function testAddsStreamingBody()
{
$f = new Handler\CurlFactory(3);
$bd = Psr7\FnStream::decorate(Psr7\stream_for('foo'), [
'getSize' => function () {
return null;
}
]);
$request = new Psr7\Request('PUT', Server::$url, [], $bd);
$f->create($request, []);
self::assertEquals(1, $_SERVER['_curl'][CURLOPT_UPLOAD]);
self::assertInternalType('callable', $_SERVER['_curl'][CURLOPT_READFUNCTION]);
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Directory /does/not/exist/so does not exist for sink value of /does/not/exist/so/error.txt
*/
public function testEnsuresDirExistsBeforeThrowingWarning()
{
$f = new Handler\CurlFactory(3);
$f->create(new Psr7\Request('GET', Server::$url), [
'sink' => '/does/not/exist/so/error.txt'
]);
}
public function testClosesIdleHandles()
{
$f = new Handler\CurlFactory(3);
$req = new Psr7\Request('GET', Server::$url);
$easy = $f->create($req, []);
$h1 = $easy->handle;
$f->release($easy);
self::assertCount(1, self::readAttribute($f, 'handles'));
$easy = $f->create($req, []);
self::assertSame($easy->handle, $h1);
$easy2 = $f->create($req, []);
$easy3 = $f->create($req, []);
$easy4 = $f->create($req, []);
$f->release($easy);
self::assertCount(1, self::readAttribute($f, 'handles'));
$f->release($easy2);
self::assertCount(2, self::readAttribute($f, 'handles'));
$f->release($easy3);
self::assertCount(3, self::readAttribute($f, 'handles'));
$f->release($easy4);
self::assertCount(3, self::readAttribute($f, 'handles'));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresOnHeadersIsCallable()
{
$req = new Psr7\Request('GET', Server::$url);
$handler = new Handler\CurlHandler();
$handler($req, ['on_headers' => 'error!']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage An error was encountered during the on_headers event
* @expectedExceptionMessage test
*/
public function testRejectsPromiseWhenOnHeadersFails()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123')
]);
$req = new Psr7\Request('GET', Server::$url);
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'on_headers' => function () {
throw new \Exception('test');
}
]);
$promise->wait();
}
public function testSuccessfullyCallsOnHeadersBeforeWritingToSink()
{
Server::flush();
Server::enqueue([
new Psr7\Response(200, ['X-Foo' => 'bar'], 'abc 123')
]);
$req = new Psr7\Request('GET', Server::$url);
$got = null;
$stream = Psr7\stream_for();
$stream = Psr7\FnStream::decorate($stream, [
'write' => function ($data) use ($stream, &$got) {
self::assertNotNull($got);
return $stream->write($data);
}
]);
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'sink' => $stream,
'on_headers' => function (ResponseInterface $res) use (&$got) {
$got = $res;
self::assertEquals('bar', $res->getHeaderLine('X-Foo'));
}
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('bar', $response->getHeaderLine('X-Foo'));
self::assertSame('abc 123', (string) $response->getBody());
}
public function testInvokesOnStatsOnSuccess()
{
Server::flush();
Server::enqueue([new Psr7\Response(200)]);
$req = new Psr7\Request('GET', Server::$url);
$gotStats = null;
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'on_stats' => function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
}
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame(200, $gotStats->getResponse()->getStatusCode());
self::assertSame(
Server::$url,
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
Server::$url,
(string) $gotStats->getRequest()->getUri()
);
self::assertGreaterThan(0, $gotStats->getTransferTime());
self::assertArrayHasKey('appconnect_time', $gotStats->getHandlerStats());
}
public function testInvokesOnStatsOnError()
{
$req = new Psr7\Request('GET', 'http://127.0.0.1:123');
$gotStats = null;
$handler = new Handler\CurlHandler();
$promise = $handler($req, [
'connect_timeout' => 0.001,
'timeout' => 0.001,
'on_stats' => function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
}
]);
$promise->wait(false);
self::assertFalse($gotStats->hasResponse());
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getRequest()->getUri()
);
self::assertInternalType('float', $gotStats->getTransferTime());
self::assertInternalType('int', $gotStats->getHandlerErrorData());
self::assertArrayHasKey('appconnect_time', $gotStats->getHandlerStats());
}
public function testRewindsBodyIfPossible()
{
$body = Psr7\stream_for(str_repeat('x', 1024 * 1024 * 2));
$body->seek(1024 * 1024);
self::assertSame(1024 * 1024, $body->tell());
$req = new Psr7\Request('POST', 'https://www.example.com', [
'Content-Length' => 1024 * 1024 * 2,
], $body);
$factory = new CurlFactory(1);
$factory->create($req, []);
self::assertSame(0, $body->tell());
}
public function testDoesNotRewindUnseekableBody()
{
$body = Psr7\stream_for(str_repeat('x', 1024 * 1024 * 2));
$body->seek(1024 * 1024);
$body = new Psr7\NoSeekStream($body);
self::assertSame(1024 * 1024, $body->tell());
$req = new Psr7\Request('POST', 'https://www.example.com', [
'Content-Length' => 1024 * 1024,
], $body);
$factory = new CurlFactory(1);
$factory->create($req, []);
self::assertSame(1024 * 1024, $body->tell());
}
public function testRelease()
{
$factory = new CurlFactory(1);
$easyHandle = new EasyHandle();
$easyHandle->handle = curl_init();
self::assertEmpty($factory->release($easyHandle));
}
}

View File

@ -0,0 +1,87 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\CurlHandler
*/
class CurlHandlerTest extends TestCase
{
protected function getHandler($options = [])
{
return new CurlHandler($options);
}
/**
* @expectedException \GuzzleHttp\Exception\ConnectException
* @expectedExceptionMessage cURL
*/
public function testCreatesCurlErrors()
{
$handler = new CurlHandler();
$request = new Request('GET', 'http://localhost:123');
$handler($request, ['timeout' => 0.001, 'connect_timeout' => 0.001])->wait();
}
public function testReusesHandles()
{
Server::flush();
$response = new response(200);
Server::enqueue([$response, $response]);
$a = new CurlHandler();
$request = new Request('GET', Server::$url);
self::assertInstanceOf('GuzzleHttp\Promise\FulfilledPromise', $a($request, []));
self::assertInstanceOf('GuzzleHttp\Promise\FulfilledPromise', $a($request, []));
}
public function testDoesSleep()
{
$response = new response(200);
Server::enqueue([$response]);
$a = new CurlHandler();
$request = new Request('GET', Server::$url);
$s = Utils::currentTime();
$a($request, ['delay' => 0.1])->wait();
self::assertGreaterThan(0.0001, Utils::currentTime() - $s);
}
public function testCreatesCurlErrorsWithContext()
{
$handler = new CurlHandler();
$request = new Request('GET', 'http://localhost:123');
$called = false;
$p = $handler($request, ['timeout' => 0.001, 'connect_timeout' => 0.001])
->otherwise(function (ConnectException $e) use (&$called) {
$called = true;
self::assertArrayHasKey('errno', $e->getHandlerContext());
});
$p->wait();
self::assertTrue($called);
}
public function testUsesContentLengthWhenOverInMemorySize()
{
Server::flush();
Server::enqueue([new Response()]);
$stream = Psr7\stream_for(str_repeat('.', 1000000));
$handler = new CurlHandler();
$request = new Request(
'PUT',
Server::$url,
['Content-Length' => 1000000],
$stream
);
$handler($request, [])->wait();
$received = Server::received()[0];
self::assertEquals(1000000, $received->getHeaderLine('Content-Length'));
self::assertFalse($received->hasHeader('Transfer-Encoding'));
}
}

View File

@ -0,0 +1,123 @@
<?php
namespace GuzzleHttp\Tests\Handler;
use GuzzleHttp\Handler\CurlMultiHandler;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
class CurlMultiHandlerTest extends TestCase
{
public function setUp()
{
$_SERVER['curl_test'] = true;
unset($_SERVER['_curl_multi']);
}
public function tearDown()
{
unset($_SERVER['_curl_multi'], $_SERVER['curl_test']);
}
public function testCanAddCustomCurlOptions()
{
Server::flush();
Server::enqueue([new Response()]);
$a = new CurlMultiHandler(['options' => [
CURLMOPT_MAXCONNECTS => 5,
]]);
$request = new Request('GET', Server::$url);
$a($request, []);
self::assertEquals(5, $_SERVER['_curl_multi'][CURLMOPT_MAXCONNECTS]);
}
public function testSendsRequest()
{
Server::enqueue([new Response()]);
$a = new CurlMultiHandler();
$request = new Request('GET', Server::$url);
$response = $a($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
}
/**
* @expectedException \GuzzleHttp\Exception\ConnectException
* @expectedExceptionMessage cURL error
*/
public function testCreatesExceptions()
{
$a = new CurlMultiHandler();
$a(new Request('GET', 'http://localhost:123'), [])->wait();
}
public function testCanSetSelectTimeout()
{
$a = new CurlMultiHandler(['select_timeout' => 2]);
self::assertEquals(2, self::readAttribute($a, 'selectTimeout'));
}
public function testCanCancel()
{
Server::flush();
$response = new Response(200);
Server::enqueue(array_fill_keys(range(0, 10), $response));
$a = new CurlMultiHandler();
$responses = [];
for ($i = 0; $i < 10; $i++) {
$response = $a(new Request('GET', Server::$url), []);
$response->cancel();
$responses[] = $response;
}
foreach ($responses as $r) {
self::assertSame('rejected', $response->getState());
}
}
public function testCannotCancelFinished()
{
Server::flush();
Server::enqueue([new Response(200)]);
$a = new CurlMultiHandler();
$response = $a(new Request('GET', Server::$url), []);
$response->wait();
$response->cancel();
self::assertSame('fulfilled', $response->getState());
}
public function testDelaysConcurrently()
{
Server::flush();
Server::enqueue([new Response()]);
$a = new CurlMultiHandler();
$expected = Utils::currentTime() + (100 / 1000);
$response = $a(new Request('GET', Server::$url), ['delay' => 100]);
$response->wait();
self::assertGreaterThanOrEqual($expected, Utils::currentTime());
}
public function testUsesTimeoutEnvironmentVariables()
{
$a = new CurlMultiHandler();
//default if no options are given and no environment variable is set
self::assertEquals(1, self::readAttribute($a, 'selectTimeout'));
putenv("GUZZLE_CURL_SELECT_TIMEOUT=3");
$a = new CurlMultiHandler();
$selectTimeout = getenv('GUZZLE_CURL_SELECT_TIMEOUT');
//Handler reads from the environment if no options are given
self::assertEquals($selectTimeout, self::readAttribute($a, 'selectTimeout'));
}
/**
* @expectedException \BadMethodCallException
*/
public function throwsWhenAccessingInvalidProperty()
{
$h = new CurlMultiHandler();
$h->foo;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler\EasyHandle;
use GuzzleHttp\Psr7;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\EasyHandle
*/
class EasyHandleTest extends TestCase
{
/**
* @expectedException \BadMethodCallException
* @expectedExceptionMessage The EasyHandle has been released
*/
public function testEnsuresHandleExists()
{
$easy = new EasyHandle;
unset($easy->handle);
$easy->handle;
}
}

View File

@ -0,0 +1,261 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\MockHandler
*/
class MockHandlerTest extends TestCase
{
public function testReturnsMockResponse()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, []);
self::assertSame($res, $p->wait());
}
public function testIsCountable()
{
$res = new Response();
$mock = new MockHandler([$res, $res]);
self::assertCount(2, $mock);
}
public function testEmptyHandlerIsCountable()
{
self::assertCount(0, new MockHandler());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresEachAppendIsValid()
{
$mock = new MockHandler(['a']);
$request = new Request('GET', 'http://example.com');
$mock($request, []);
}
public function testCanQueueExceptions()
{
$e = new \Exception('a');
$mock = new MockHandler([$e]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, []);
try {
$p->wait();
self::fail();
} catch (\Exception $e2) {
self::assertSame($e, $e2);
}
}
public function testCanGetLastRequestAndOptions()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$mock($request, ['foo' => 'bar']);
self::assertSame($request, $mock->getLastRequest());
self::assertSame(['foo' => 'bar'], $mock->getLastOptions());
}
public function testSinkFilename()
{
$filename = sys_get_temp_dir() . '/mock_test_' . uniqid();
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $filename]);
$p->wait();
self::assertFileExists($filename);
self::assertStringEqualsFile($filename, 'TEST CONTENT');
unlink($filename);
}
public function testSinkResource()
{
$file = tmpfile();
$meta = stream_get_meta_data($file);
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $file]);
$p->wait();
self::assertFileExists($meta['uri']);
self::assertStringEqualsFile($meta['uri'], 'TEST CONTENT');
}
public function testSinkStream()
{
$stream = new \GuzzleHttp\Psr7\Stream(tmpfile());
$res = new Response(200, [], 'TEST CONTENT');
$mock = new MockHandler([$res]);
$request = new Request('GET', '/');
$p = $mock($request, ['sink' => $stream]);
$p->wait();
self::assertFileExists($stream->getMetadata('uri'));
self::assertStringEqualsFile($stream->getMetadata('uri'), 'TEST CONTENT');
}
public function testCanEnqueueCallables()
{
$r = new Response();
$fn = function ($req, $o) use ($r) {
return $r;
};
$mock = new MockHandler([$fn]);
$request = new Request('GET', 'http://example.com');
$p = $mock($request, ['foo' => 'bar']);
self::assertSame($r, $p->wait());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresOnHeadersIsCallable()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$mock($request, ['on_headers' => 'error!']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage An error was encountered during the on_headers event
* @expectedExceptionMessage test
*/
public function testRejectsPromiseWhenOnHeadersFails()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
$promise = $mock($request, [
'on_headers' => function () {
throw new \Exception('test');
}
]);
$promise->wait();
}
public function testInvokesOnFulfilled()
{
$res = new Response();
$mock = new MockHandler([$res], function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$mock($request, [])->wait();
self::assertSame($res, $c);
}
public function testInvokesOnRejected()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$mock($request, [])->wait(false);
self::assertSame($e, $c);
}
/**
* @expectedException \OutOfBoundsException
*/
public function testThrowsWhenNoMoreResponses()
{
$mock = new MockHandler();
$request = new Request('GET', 'http://example.com');
$mock($request, []);
}
/**
* @expectedException \GuzzleHttp\Exception\BadResponseException
*/
public function testCanCreateWithDefaultMiddleware()
{
$r = new Response(500);
$mock = MockHandler::createWithMiddleware([$r]);
$request = new Request('GET', 'http://example.com');
$mock($request, ['http_errors' => true])->wait();
}
public function testInvokesOnStatsFunctionForResponse()
{
$res = new Response();
$mock = new MockHandler([$res]);
$request = new Request('GET', 'http://example.com');
/** @var TransferStats|null $stats */
$stats = null;
$onStats = function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$p = $mock($request, ['on_stats' => $onStats]);
$p->wait();
self::assertSame($res, $stats->getResponse());
self::assertSame($request, $stats->getRequest());
}
public function testInvokesOnStatsFunctionForError()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
/** @var TransferStats|null $stats */
$stats = null;
$onStats = function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$mock($request, ['on_stats' => $onStats])->wait(false);
self::assertSame($e, $stats->getHandlerErrorData());
self::assertNull($stats->getResponse());
self::assertSame($request, $stats->getRequest());
}
public function testTransferTime()
{
$e = new \Exception('a');
$c = null;
$mock = new MockHandler([$e], null, function ($v) use (&$c) {
$c = $v;
});
$request = new Request('GET', 'http://example.com');
$stats = null;
$onStats = function (TransferStats $s) use (&$stats) {
$stats = $s;
};
$mock($request, [ 'on_stats' => $onStats, 'transfer_time' => 0.4 ])->wait(false);
self::assertEquals(0.4, $stats->getTransferTime());
}
public function testResetQueue()
{
$mock = new MockHandler([new Response(200), new Response(204)]);
self::assertCount(2, $mock);
$mock->reset();
self::assertEmpty($mock);
$mock->append(new Response(500));
self::assertCount(1, $mock);
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Handler\Proxy;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\Handler\Proxy
*/
class ProxyTest extends TestCase
{
public function testSendsToNonSync()
{
$a = $b = null;
$m1 = new MockHandler([function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapSync($m1, $m2);
$h(new Request('GET', 'http://foo.com'), []);
self::assertNotNull($a);
self::assertNull($b);
}
public function testSendsToSync()
{
$a = $b = null;
$m1 = new MockHandler([function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapSync($m1, $m2);
$h(new Request('GET', 'http://foo.com'), [RequestOptions::SYNCHRONOUS => true]);
self::assertNull($a);
self::assertNotNull($b);
}
public function testSendsToStreaming()
{
$a = $b = null;
$m1 = new MockHandler([function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapStreaming($m1, $m2);
$h(new Request('GET', 'http://foo.com'), []);
self::assertNotNull($a);
self::assertNull($b);
}
public function testSendsToNonStreaming()
{
$a = $b = null;
$m1 = new MockHandler([function ($v) use (&$a) {
$a = $v;
}]);
$m2 = new MockHandler([function ($v) use (&$b) {
$b = $v;
}]);
$h = Proxy::wrapStreaming($m1, $m2);
$h(new Request('GET', 'http://foo.com'), ['stream' => true]);
self::assertNull($a);
self::assertNotNull($b);
}
}

View File

@ -0,0 +1,689 @@
<?php
namespace GuzzleHttp\Test\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\StreamHandler;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Tests\Server;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
/**
* @covers \GuzzleHttp\Handler\StreamHandler
*/
class StreamHandlerTest extends TestCase
{
private function queueRes()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], 'hi there')
]);
}
public function testReturnsResponseForSuccessfulRequest()
{
$this->queueRes();
$handler = new StreamHandler();
$response = $handler(
new Request('GET', Server::$url, ['Foo' => 'Bar']),
[]
)->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('8', $response->getHeaderLine('Content-Length'));
self::assertSame('hi there', (string) $response->getBody());
$sent = Server::received()[0];
self::assertSame('GET', $sent->getMethod());
self::assertSame('/', $sent->getUri()->getPath());
self::assertSame('127.0.0.1:8126', $sent->getHeaderLine('Host'));
self::assertSame('Bar', $sent->getHeaderLine('foo'));
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
*/
public function testAddsErrorToResponse()
{
$handler = new StreamHandler();
$handler(
new Request('GET', 'http://localhost:123'),
['timeout' => 0.01]
)->wait();
}
public function testStreamAttributeKeepsStreamOpen()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request(
'PUT',
Server::$url . 'foo?baz=bar',
['Foo' => 'Bar'],
'test'
);
$response = $handler($request, ['stream' => true])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('8', $response->getHeaderLine('Content-Length'));
$body = $response->getBody();
$stream = $body->detach();
self::assertInternalType('resource', $stream);
self::assertSame('http', stream_get_meta_data($stream)['wrapper_type']);
self::assertSame('hi there', stream_get_contents($stream));
fclose($stream);
$sent = Server::received()[0];
self::assertSame('PUT', $sent->getMethod());
self::assertSame('http://127.0.0.1:8126/foo?baz=bar', (string) $sent->getUri());
self::assertSame('Bar', $sent->getHeaderLine('Foo'));
self::assertSame('test', (string) $sent->getBody());
}
public function testDrainsResponseIntoTempStream()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('php://temp', stream_get_meta_data($stream)['uri']);
self::assertSame('hi', fread($stream, 2));
fclose($stream);
}
public function testDrainsResponseIntoSaveToBody()
{
$r = fopen('php://temp', 'r+');
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $r])->wait();
$body = $response->getBody()->detach();
self::assertSame('php://temp', stream_get_meta_data($body)['uri']);
self::assertSame('hi', fread($body, 2));
self::assertSame(' there', stream_get_contents($r));
fclose($r);
}
public function testDrainsResponseIntoSaveToBodyAtPath()
{
$tmpfname = tempnam('/tmp', 'save_to_path');
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $tmpfname])->wait();
$body = $response->getBody();
self::assertSame($tmpfname, $body->getMetadata('uri'));
self::assertSame('hi', $body->read(2));
$body->close();
unlink($tmpfname);
}
public function testDrainsResponseIntoSaveToBodyAtNonExistentPath()
{
$tmpfname = tempnam('/tmp', 'save_to_path');
unlink($tmpfname);
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['sink' => $tmpfname])->wait();
$body = $response->getBody();
self::assertSame($tmpfname, $body->getMetadata('uri'));
self::assertSame('hi', $body->read(2));
$body->close();
unlink($tmpfname);
}
public function testDrainsResponseAndReadsOnlyContentLengthBytes()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], 'hi there... This has way too much data!')
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('hi there', stream_get_contents($stream));
fclose($stream);
}
public function testDoesNotDrainWhenHeadRequest()
{
Server::flush();
// Say the content-length is 8, but return no response.
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => 8,
], '')
]);
$handler = new StreamHandler();
$request = new Request('HEAD', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('', stream_get_contents($stream));
fclose($stream);
}
public function testAutomaticallyDecompressGzip()
{
Server::flush();
$content = gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => strlen($content),
], $content)
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true])->wait();
self::assertSame('test', (string) $response->getBody());
self::assertFalse($response->hasHeader('content-encoding'));
self::assertTrue(!$response->hasHeader('content-length') || $response->getHeaderLine('content-length') == $response->getBody()->getSize());
}
public function testReportsOriginalSizeAndContentEncodingAfterDecoding()
{
Server::flush();
$content = gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => strlen($content),
], $content)
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => true])->wait();
self::assertSame(
'gzip',
$response->getHeaderLine('x-encoded-content-encoding')
);
self::assertSame(
strlen($content),
(int) $response->getHeaderLine('x-encoded-content-length')
);
}
public function testDoesNotForceGzipDecode()
{
Server::flush();
$content = gzencode('test');
Server::enqueue([
new Response(200, [
'Content-Encoding' => 'gzip',
'Content-Length' => strlen($content),
], $content)
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, ['decode_content' => false])->wait();
self::assertSame($content, (string) $response->getBody());
self::assertSame('gzip', $response->getHeaderLine('content-encoding'));
self::assertEquals(strlen($content), $response->getHeaderLine('content-length'));
}
public function testProtocolVersion()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('GET', Server::$url, [], null, '1.0');
$handler($request, []);
self::assertSame('1.0', Server::received()[0]->getProtocolVersion());
}
protected function getSendResult(array $opts)
{
$this->queueRes();
$handler = new StreamHandler();
$opts['stream'] = true;
$request = new Request('GET', Server::$url);
return $handler($request, $opts)->wait();
}
/**
* @expectedException \GuzzleHttp\Exception\ConnectException
* @expectedExceptionMessage Connection refused
*/
public function testAddsProxy()
{
$this->getSendResult(['proxy' => '127.0.0.1:8125']);
}
public function testAddsProxyByProtocol()
{
$url = str_replace('http', 'tcp', Server::$url);
// Workaround until #1823 is fixed properly
$url = rtrim($url, '/');
$res = $this->getSendResult(['proxy' => ['http' => $url]]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertSame($url, $opts['http']['proxy']);
}
public function testAddsProxyButHonorsNoProxy()
{
$url = str_replace('http', 'tcp', Server::$url);
$res = $this->getSendResult(['proxy' => [
'http' => $url,
'no' => ['*']
]]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertArrayNotHasKey('proxy', $opts['http']);
}
public function testAddsTimeout()
{
$res = $this->getSendResult(['stream' => true, 'timeout' => 200]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertEquals(200, $opts['http']['timeout']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage SSL CA bundle not found: /does/not/exist
*/
public function testVerifiesVerifyIsValidIfPath()
{
$this->getSendResult(['verify' => '/does/not/exist']);
}
public function testVerifyCanBeDisabled()
{
$handler = $this->getSendResult(['verify' => false]);
self::assertInstanceOf('GuzzleHttp\Psr7\Response', $handler);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage SSL certificate not found: /does/not/exist
*/
public function testVerifiesCertIfValidPath()
{
$this->getSendResult(['cert' => '/does/not/exist']);
}
public function testVerifyCanBeSetToPath()
{
$path = $path = \GuzzleHttp\default_ca_bundle();
$res = $this->getSendResult(['verify' => $path]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertTrue($opts['ssl']['verify_peer']);
self::assertTrue($opts['ssl']['verify_peer_name']);
self::assertSame($path, $opts['ssl']['cafile']);
self::assertFileExists($opts['ssl']['cafile']);
}
public function testUsesSystemDefaultBundle()
{
$path = $path = \GuzzleHttp\default_ca_bundle();
$res = $this->getSendResult(['verify' => true]);
$opts = stream_context_get_options($res->getBody()->detach());
if (PHP_VERSION_ID < 50600) {
self::assertSame($path, $opts['ssl']['cafile']);
} else {
self::assertArrayNotHasKey('cafile', $opts['ssl']);
}
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid verify request option
*/
public function testEnsuresVerifyOptionIsValid()
{
$this->getSendResult(['verify' => 10]);
}
public function testCanSetPasswordWhenSettingCert()
{
$path = __FILE__;
$res = $this->getSendResult(['cert' => [$path, 'foo']]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertSame($path, $opts['ssl']['local_cert']);
self::assertSame('foo', $opts['ssl']['passphrase']);
}
public function testDebugAttributeWritesToStream()
{
$this->queueRes();
$f = fopen('php://temp', 'w+');
$this->getSendResult(['debug' => $f]);
fseek($f, 0);
$contents = stream_get_contents($f);
self::assertContains('<GET http://127.0.0.1:8126/> [CONNECT]', $contents);
self::assertContains('<GET http://127.0.0.1:8126/> [FILE_SIZE_IS]', $contents);
self::assertContains('<GET http://127.0.0.1:8126/> [PROGRESS]', $contents);
}
public function testDebugAttributeWritesStreamInfoToBuffer()
{
$called = false;
$this->queueRes();
$buffer = fopen('php://temp', 'r+');
$this->getSendResult([
'progress' => function () use (&$called) {
$called = true;
},
'debug' => $buffer,
]);
fseek($buffer, 0);
$contents = stream_get_contents($buffer);
self::assertContains('<GET http://127.0.0.1:8126/> [CONNECT]', $contents);
self::assertContains('<GET http://127.0.0.1:8126/> [FILE_SIZE_IS] message: "Content-Length: 8"', $contents);
self::assertContains('<GET http://127.0.0.1:8126/> [PROGRESS] bytes_max: "8"', $contents);
self::assertTrue($called);
}
public function testEmitsProgressInformation()
{
$called = [];
$this->queueRes();
$this->getSendResult([
'progress' => function () use (&$called) {
$called[] = func_get_args();
},
]);
self::assertNotEmpty($called);
self::assertEquals(8, $called[0][0]);
self::assertEquals(0, $called[0][1]);
}
public function testEmitsProgressInformationAndDebugInformation()
{
$called = [];
$this->queueRes();
$buffer = fopen('php://memory', 'w+');
$this->getSendResult([
'debug' => $buffer,
'progress' => function () use (&$called) {
$called[] = func_get_args();
},
]);
self::assertNotEmpty($called);
self::assertEquals(8, $called[0][0]);
self::assertEquals(0, $called[0][1]);
rewind($buffer);
self::assertNotEmpty(stream_get_contents($buffer));
fclose($buffer);
}
public function testPerformsShallowMergeOfCustomContextOptions()
{
$res = $this->getSendResult([
'stream_context' => [
'http' => [
'request_fulluri' => true,
'method' => 'HEAD',
],
'socket' => [
'bindto' => '127.0.0.1:0',
],
'ssl' => [
'verify_peer' => false,
],
],
]);
$opts = stream_context_get_options($res->getBody()->detach());
self::assertSame('HEAD', $opts['http']['method']);
self::assertTrue($opts['http']['request_fulluri']);
self::assertSame('127.0.0.1:0', $opts['socket']['bindto']);
self::assertFalse($opts['ssl']['verify_peer']);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage stream_context must be an array
*/
public function testEnsuresThatStreamContextIsAnArray()
{
$this->getSendResult(['stream_context' => 'foo']);
}
public function testDoesNotAddContentTypeByDefault()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, ['Content-Length' => 3], 'foo');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals('', $req->getHeaderLine('Content-Type'));
self::assertEquals(3, $req->getHeaderLine('Content-Length'));
}
public function testAddsContentLengthByDefault()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, [], 'foo');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals(3, $req->getHeaderLine('Content-Length'));
}
public function testAddsContentLengthEvenWhenEmpty()
{
$this->queueRes();
$handler = new StreamHandler();
$request = new Request('PUT', Server::$url, [], '');
$handler($request, []);
$req = Server::received()[0];
self::assertEquals(0, $req->getHeaderLine('Content-Length'));
}
public function testSupports100Continue()
{
Server::flush();
$response = new Response(200, ['Test' => 'Hello', 'Content-Length' => '4'], 'test');
Server::enqueue([$response]);
$request = new Request('PUT', Server::$url, ['Expect' => '100-Continue'], 'test');
$handler = new StreamHandler();
$response = $handler($request, [])->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('Hello', $response->getHeaderLine('Test'));
self::assertSame('4', $response->getHeaderLine('Content-Length'));
self::assertSame('test', (string) $response->getBody());
}
public function testDoesSleep()
{
$response = new response(200);
Server::enqueue([$response]);
$a = new StreamHandler();
$request = new Request('GET', Server::$url);
$s = Utils::currentTime();
$a($request, ['delay' => 0.1])->wait();
self::assertGreaterThan(0.0001, Utils::currentTime() - $s);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresOnHeadersIsCallable()
{
$req = new Request('GET', Server::$url);
$handler = new StreamHandler();
$handler($req, ['on_headers' => 'error!']);
}
/**
* @expectedException \GuzzleHttp\Exception\RequestException
* @expectedExceptionMessage An error was encountered during the on_headers event
* @expectedExceptionMessage test
*/
public function testRejectsPromiseWhenOnHeadersFails()
{
Server::flush();
Server::enqueue([
new Response(200, ['X-Foo' => 'bar'], 'abc 123')
]);
$req = new Request('GET', Server::$url);
$handler = new StreamHandler();
$promise = $handler($req, [
'on_headers' => function () {
throw new \Exception('test');
}
]);
$promise->wait();
}
public function testSuccessfullyCallsOnHeadersBeforeWritingToSink()
{
Server::flush();
Server::enqueue([
new Response(200, ['X-Foo' => 'bar'], 'abc 123')
]);
$req = new Request('GET', Server::$url);
$got = null;
$stream = Psr7\stream_for();
$stream = FnStream::decorate($stream, [
'write' => function ($data) use ($stream, &$got) {
self::assertNotNull($got);
return $stream->write($data);
}
]);
$handler = new StreamHandler();
$promise = $handler($req, [
'sink' => $stream,
'on_headers' => function (ResponseInterface $res) use (&$got) {
$got = $res;
self::assertSame('bar', $res->getHeaderLine('X-Foo'));
}
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('bar', $response->getHeaderLine('X-Foo'));
self::assertSame('abc 123', (string) $response->getBody());
}
public function testInvokesOnStatsOnSuccess()
{
Server::flush();
Server::enqueue([new Psr7\Response(200)]);
$req = new Psr7\Request('GET', Server::$url);
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'on_stats' => function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
}
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame(200, $gotStats->getResponse()->getStatusCode());
self::assertSame(
Server::$url,
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
Server::$url,
(string) $gotStats->getRequest()->getUri()
);
self::assertGreaterThan(0, $gotStats->getTransferTime());
}
public function testInvokesOnStatsOnError()
{
$req = new Psr7\Request('GET', 'http://127.0.0.1:123');
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'connect_timeout' => 0.001,
'timeout' => 0.001,
'on_stats' => function (TransferStats $stats) use (&$gotStats) {
$gotStats = $stats;
}
]);
$promise->wait(false);
self::assertFalse($gotStats->hasResponse());
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getEffectiveUri()
);
self::assertSame(
'http://127.0.0.1:123',
(string) $gotStats->getRequest()->getUri()
);
self::assertInternalType('float', $gotStats->getTransferTime());
self::assertInstanceOf(
ConnectException::class,
$gotStats->getHandlerErrorData()
);
}
public function testStreamIgnoresZeroTimeout()
{
Server::flush();
Server::enqueue([new Psr7\Response(200)]);
$req = new Psr7\Request('GET', Server::$url);
$gotStats = null;
$handler = new StreamHandler();
$promise = $handler($req, [
'connect_timeout' => 10,
'timeout' => 0
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testDrainsResponseAndReadsAllContentWhenContentLengthIsZero()
{
Server::flush();
Server::enqueue([
new Response(200, [
'Foo' => 'Bar',
'Content-Length' => '0',
], 'hi there... This has a lot of data!')
]);
$handler = new StreamHandler();
$request = new Request('GET', Server::$url);
$response = $handler($request, [])->wait();
$body = $response->getBody();
$stream = $body->detach();
self::assertSame('hi there... This has a lot of data!', stream_get_contents($stream));
fclose($stream);
}
public function testHonorsReadTimeout()
{
Server::flush();
$handler = new StreamHandler();
$response = $handler(
new Request('GET', Server::$url . 'guzzle-server/read-timeout'),
[
RequestOptions::READ_TIMEOUT => 1,
RequestOptions::STREAM => true,
]
)->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
$body = $response->getBody()->detach();
$line = fgets($body);
self::assertSame("sleeping 60 seconds ...\n", $line);
$line = fgets($body);
self::assertFalse($line);
self::assertTrue(stream_get_meta_data($body)['timed_out']);
self::assertFalse(feof($body));
}
}

View File

@ -0,0 +1,214 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
class HandlerStackTest extends TestCase
{
public function testSetsHandlerInCtor()
{
$f = function () {
};
$m1 = function () {
};
$h = new HandlerStack($f, [$m1]);
self::assertTrue($h->hasHandler());
}
/**
* @doesNotPerformAssertions
*/
public function testCanSetDifferentHandlerAfterConstruction()
{
$f = function () {
};
$h = new HandlerStack();
$h->setHandler($f);
$h->resolve();
}
/**
* @expectedException \LogicException
*/
public function testEnsuresHandlerIsSet()
{
$h = new HandlerStack();
$h->resolve();
}
public function testPushInOrder()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2]);
$builder->push($meths[3]);
$builder->push($meths[4]);
$composed = $builder->resolve();
self::assertSame('Hello - test123', $composed('test'));
self::assertSame(
[['a', 'test'], ['b', 'test1'], ['c', 'test12']],
$meths[0]
);
}
public function testUnshiftsInReverseOrder()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->unshift($meths[2]);
$builder->unshift($meths[3]);
$builder->unshift($meths[4]);
$composed = $builder->resolve();
self::assertSame('Hello - test321', $composed('test'));
self::assertSame(
[['c', 'test'], ['b', 'test3'], ['a', 'test32']],
$meths[0]
);
}
public function testCanRemoveMiddlewareByInstance()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2]);
$builder->push($meths[2]);
$builder->push($meths[3]);
$builder->push($meths[4]);
$builder->push($meths[2]);
$builder->remove($meths[3]);
$composed = $builder->resolve();
self::assertSame('Hello - test1131', $composed('test'));
}
public function testCanPrintMiddleware()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'a');
$builder->push([__CLASS__, 'foo']);
$builder->push([$this, 'bar']);
$builder->push(__CLASS__ . '::' . 'foo');
$lines = explode("\n", (string) $builder);
self::assertContains("> 4) Name: 'a', Function: callable(", $lines[0]);
self::assertContains("> 3) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[1]);
self::assertContains("> 2) Name: '', Function: callable(['GuzzleHttp\\Tests\\HandlerStackTest', 'bar'])", $lines[2]);
self::assertContains("> 1) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[3]);
self::assertContains("< 0) Handler: callable(", $lines[4]);
self::assertContains("< 1) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[5]);
self::assertContains("< 2) Name: '', Function: callable(['GuzzleHttp\\Tests\\HandlerStackTest', 'bar'])", $lines[6]);
self::assertContains("< 3) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[7]);
self::assertContains("< 4) Name: 'a', Function: callable(", $lines[8]);
}
public function testCanAddBeforeByName()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'foo');
$builder->before('foo', $meths[3], 'baz');
$builder->before('baz', $meths[4], 'bar');
$builder->before('baz', $meths[4], 'qux');
$lines = explode("\n", (string) $builder);
self::assertContains('> 4) Name: \'bar\'', $lines[0]);
self::assertContains('> 3) Name: \'qux\'', $lines[1]);
self::assertContains('> 2) Name: \'baz\'', $lines[2]);
self::assertContains('> 1) Name: \'foo\'', $lines[3]);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresHandlerExistsByName()
{
$builder = new HandlerStack();
$builder->before('foo', function () {
});
}
public function testCanAddAfterByName()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'a');
$builder->push($meths[3], 'b');
$builder->after('a', $meths[4], 'c');
$builder->after('b', $meths[4], 'd');
$lines = explode("\n", (string) $builder);
self::assertContains('4) Name: \'a\'', $lines[0]);
self::assertContains('3) Name: \'c\'', $lines[1]);
self::assertContains('2) Name: \'b\'', $lines[2]);
self::assertContains('1) Name: \'d\'', $lines[3]);
}
public function testPicksUpCookiesFromRedirects()
{
$mock = new MockHandler([
new Response(301, [
'Location' => 'http://foo.com/baz',
'Set-Cookie' => 'foo=bar; Domain=foo.com'
]),
new Response(200)
]);
$handler = HandlerStack::create($mock);
$request = new Request('GET', 'http://foo.com/bar');
$jar = new CookieJar();
$response = $handler($request, [
'allow_redirects' => true,
'cookies' => $jar
])->wait();
self::assertSame(200, $response->getStatusCode());
$lastRequest = $mock->getLastRequest();
self::assertSame('http://foo.com/baz', (string) $lastRequest->getUri());
self::assertSame('foo=bar', $lastRequest->getHeaderLine('Cookie'));
}
private function getFunctions()
{
$calls = [];
$a = function (callable $next) use (&$calls) {
return function ($v) use ($next, &$calls) {
$calls[] = ['a', $v];
return $next($v . '1');
};
};
$b = function (callable $next) use (&$calls) {
return function ($v) use ($next, &$calls) {
$calls[] = ['b', $v];
return $next($v . '2');
};
};
$c = function (callable $next) use (&$calls) {
return function ($v) use ($next, &$calls) {
$calls[] = ['c', $v];
return $next($v . '3');
};
};
$handler = function ($v) {
return 'Hello - ' . $v;
};
return [&$calls, $handler, $a, $b, $c];
}
public static function foo()
{
}
public function bar()
{
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace GuzzleHttp\Test;
use GuzzleHttp\Psr7;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
class InternalUtilsTest extends TestCase
{
public function testCurrentTime()
{
self::assertGreaterThan(0, Utils::currentTime());
}
public function testIdnConvert()
{
$uri = Psr7\uri_for('https://яндекс.рф/images');
$uri = Utils::idnUriConvert($uri);
self::assertSame('xn--d1acpjx3f.xn--p1ai', $uri->getHost());
}
}

View File

@ -0,0 +1,93 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\MessageFormatter
*/
class MessageFormatterTest extends TestCase
{
public function testCreatesWithClfByDefault()
{
$f = new MessageFormatter();
self::assertEquals(MessageFormatter::CLF, self::readAttribute($f, 'template'));
$f = new MessageFormatter(null);
self::assertEquals(MessageFormatter::CLF, self::readAttribute($f, 'template'));
}
public function dateProvider()
{
return [
['{ts}', '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/'],
['{date_iso_8601}', '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/'],
['{date_common_log}', '/^\d\d\/[A-Z][a-z]{2}\/[0-9]{4}/']
];
}
/**
* @dataProvider dateProvider
*/
public function testFormatsTimestamps($format, $pattern)
{
$f = new MessageFormatter($format);
$request = new Request('GET', '/');
$result = $f->format($request);
self::assertRegExp($pattern, $result);
}
public function formatProvider()
{
$request = new Request('PUT', '/', ['x-test' => 'abc'], Psr7\stream_for('foo'));
$response = new Response(200, ['X-Baz' => 'Bar'], Psr7\stream_for('baz'));
$err = new RequestException('Test', $request, $response);
return [
['{request}', [$request], Psr7\str($request)],
['{response}', [$request, $response], Psr7\str($response)],
['{request} {response}', [$request, $response], Psr7\str($request) . ' ' . Psr7\str($response)],
// Empty response yields no value
['{request} {response}', [$request], Psr7\str($request) . ' '],
['{req_headers}', [$request], "PUT / HTTP/1.1\r\nx-test: abc"],
['{res_headers}', [$request, $response], "HTTP/1.1 200 OK\r\nX-Baz: Bar"],
['{res_headers}', [$request], 'NULL'],
['{req_body}', [$request], 'foo'],
['{res_body}', [$request, $response], 'baz'],
['{res_body}', [$request], 'NULL'],
['{method}', [$request], $request->getMethod()],
['{url}', [$request], $request->getUri()],
['{target}', [$request], $request->getRequestTarget()],
['{req_version}', [$request], $request->getProtocolVersion()],
['{res_version}', [$request, $response], $response->getProtocolVersion()],
['{res_version}', [$request], 'NULL'],
['{host}', [$request], $request->getHeaderLine('Host')],
['{hostname}', [$request, $response], gethostname()],
['{hostname}{hostname}', [$request, $response], gethostname() . gethostname()],
['{code}', [$request, $response], $response->getStatusCode()],
['{code}', [$request], 'NULL'],
['{phrase}', [$request, $response], $response->getReasonPhrase()],
['{phrase}', [$request], 'NULL'],
['{error}', [$request, $response, $err], 'Test'],
['{error}', [$request], 'NULL'],
['{req_header_x-test}', [$request], 'abc'],
['{req_header_x-not}', [$request], ''],
['{res_header_X-Baz}', [$request, $response], 'Bar'],
['{res_header_x-not}', [$request, $response], ''],
['{res_header_X-Baz}', [$request], 'NULL'],
];
}
/**
* @dataProvider formatProvider
*/
public function testFormatsMessages($template, $args, $result)
{
$f = new MessageFormatter($template);
self::assertSame((string) $result, call_user_func_array([$f, 'format'], $args));
}
}

View File

@ -0,0 +1,217 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\Test\TestLogger;
class MiddlewareTest extends TestCase
{
public function testAddsCookiesToRequests()
{
$jar = new CookieJar();
$m = Middleware::cookies($jar);
$h = new MockHandler(
[
function (RequestInterface $request) {
return new Response(200, [
'Set-Cookie' => (string) new SetCookie([
'Name' => 'name',
'Value' => 'value',
'Domain' => 'foo.com'
])
]);
}
]
);
$f = $m($h);
$f(new Request('GET', 'http://foo.com'), ['cookies' => $jar])->wait();
self::assertCount(1, $jar);
}
/**
* @expectedException \GuzzleHttp\Exception\ClientException
*/
public function testThrowsExceptionOnHttpClientError()
{
$m = Middleware::httpErrors();
$h = new MockHandler([new Response(404)]);
$f = $m($h);
$p = $f(new Request('GET', 'http://foo.com'), ['http_errors' => true]);
self::assertSame('pending', $p->getState());
$p->wait();
self::assertSame('rejected', $p->getState());
}
/**
* @expectedException \GuzzleHttp\Exception\ServerException
*/
public function testThrowsExceptionOnHttpServerError()
{
$m = Middleware::httpErrors();
$h = new MockHandler([new Response(500)]);
$f = $m($h);
$p = $f(new Request('GET', 'http://foo.com'), ['http_errors' => true]);
self::assertSame('pending', $p->getState());
$p->wait();
self::assertSame('rejected', $p->getState());
}
/**
* @dataProvider getHistoryUseCases
*/
public function testTracksHistory($container)
{
$m = Middleware::history($container);
$h = new MockHandler([new Response(200), new Response(201)]);
$f = $m($h);
$p1 = $f(new Request('GET', 'http://foo.com'), ['headers' => ['foo' => 'bar']]);
$p2 = $f(new Request('HEAD', 'http://foo.com'), ['headers' => ['foo' => 'baz']]);
$p1->wait();
$p2->wait();
self::assertCount(2, $container);
self::assertSame(200, $container[0]['response']->getStatusCode());
self::assertSame(201, $container[1]['response']->getStatusCode());
self::assertSame('GET', $container[0]['request']->getMethod());
self::assertSame('HEAD', $container[1]['request']->getMethod());
self::assertSame('bar', $container[0]['options']['headers']['foo']);
self::assertSame('baz', $container[1]['options']['headers']['foo']);
}
public function getHistoryUseCases()
{
return [
[[]], // 1. Container is an array
[new \ArrayObject()] // 2. Container is an ArrayObject
];
}
public function testTracksHistoryForFailures()
{
$container = [];
$m = Middleware::history($container);
$request = new Request('GET', 'http://foo.com');
$h = new MockHandler([new RequestException('error', $request)]);
$f = $m($h);
$f($request, [])->wait(false);
self::assertCount(1, $container);
self::assertSame('GET', $container[0]['request']->getMethod());
self::assertInstanceOf(RequestException::class, $container[0]['error']);
}
public function testTapsBeforeAndAfter()
{
$calls = [];
$m = function ($handler) use (&$calls) {
return function ($request, $options) use ($handler, &$calls) {
$calls[] = '2';
return $handler($request, $options);
};
};
$m2 = Middleware::tap(
function (RequestInterface $request, array $options) use (&$calls) {
$calls[] = '1';
},
function (RequestInterface $request, array $options, PromiseInterface $p) use (&$calls) {
$calls[] = '3';
}
);
$h = new MockHandler([new Response()]);
$b = new HandlerStack($h);
$b->push($m2);
$b->push($m);
$comp = $b->resolve();
$p = $comp(new Request('GET', 'http://foo.com'), []);
self::assertSame('123', implode('', $calls));
self::assertInstanceOf(PromiseInterface::class, $p);
self::assertSame(200, $p->wait()->getStatusCode());
}
public function testMapsRequest()
{
$h = new MockHandler([
function (RequestInterface $request, array $options) {
self::assertSame('foo', $request->getHeaderLine('Bar'));
return new Response(200);
}
]);
$stack = new HandlerStack($h);
$stack->push(Middleware::mapRequest(function (RequestInterface $request) {
return $request->withHeader('Bar', 'foo');
}));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
self::assertInstanceOf(PromiseInterface::class, $p);
}
public function testMapsResponse()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
return $response->withHeader('Bar', 'foo');
}));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertSame('foo', $p->wait()->getHeaderLine('Bar'));
}
public function testLogsRequestsAndResponses()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter();
$stack->push(Middleware::log($logger, $formatter));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertCount(1, $logger->records);
self::assertContains('"PUT / HTTP/1.1" 200', $logger->records[0]['message']);
}
public function testLogsRequestsAndResponsesCustomLevel()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter();
$stack->push(Middleware::log($logger, $formatter, 'debug'));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertCount(1, $logger->records);
self::assertContains('"PUT / HTTP/1.1" 200', $logger->records[0]['message']);
self::assertSame('debug', $logger->records[0]['level']);
}
public function testLogsRequestsAndErrors()
{
$h = new MockHandler([new Response(404)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter('{code} {error}');
$stack->push(Middleware::log($logger, $formatter));
$stack->push(Middleware::httpErrors());
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), ['http_errors' => true]);
$p->wait(false);
self::assertCount(1, $logger->records);
self::assertContains('PUT http://www.google.com', $logger->records[0]['message']);
self::assertContains('404 Not Found', $logger->records[0]['message']);
}
}

View File

@ -0,0 +1,193 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Pool;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
class PoolTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesIterable()
{
$p = new Pool(new Client(), 'foo');
$p->promise()->wait();
}
/**
* @expectedException \InvalidArgumentException
*/
public function testValidatesEachElement()
{
$c = new Client();
$requests = ['foo'];
$p = new Pool($c, new \ArrayIterator($requests));
$p->promise()->wait();
}
/**
* @doesNotPerformAssertions
*/
public function testSendsAndRealizesFuture()
{
$c = $this->getClient();
$p = new Pool($c, [new Request('GET', 'http://example.com')]);
$p->promise()->wait();
}
/**
* @doesNotPerformAssertions
*/
public function testExecutesPendingWhenWaiting()
{
$r1 = new Promise(function () use (&$r1) {
$r1->resolve(new Response());
});
$r2 = new Promise(function () use (&$r2) {
$r2->resolve(new Response());
});
$r3 = new Promise(function () use (&$r3) {
$r3->resolve(new Response());
});
$handler = new MockHandler([$r1, $r2, $r3]);
$c = new Client(['handler' => $handler]);
$p = new Pool($c, [
new Request('GET', 'http://example.com'),
new Request('GET', 'http://example.com'),
new Request('GET', 'http://example.com'),
], ['pool_size' => 2]);
$p->promise()->wait();
}
public function testUsesRequestOptions()
{
$h = [];
$handler = new MockHandler([
function (RequestInterface $request) use (&$h) {
$h[] = $request;
return new Response();
}
]);
$c = new Client(['handler' => $handler]);
$opts = ['options' => ['headers' => ['x-foo' => 'bar']]];
$p = new Pool($c, [new Request('GET', 'http://example.com')], $opts);
$p->promise()->wait();
self::assertCount(1, $h);
self::assertTrue($h[0]->hasHeader('x-foo'));
}
public function testCanProvideCallablesThatReturnResponses()
{
$h = [];
$handler = new MockHandler([
function (RequestInterface $request) use (&$h) {
$h[] = $request;
return new Response();
}
]);
$c = new Client(['handler' => $handler]);
$optHistory = [];
$fn = function (array $opts) use (&$optHistory, $c) {
$optHistory = $opts;
return $c->request('GET', 'http://example.com', $opts);
};
$opts = ['options' => ['headers' => ['x-foo' => 'bar']]];
$p = new Pool($c, [$fn], $opts);
$p->promise()->wait();
self::assertCount(1, $h);
self::assertTrue($h[0]->hasHeader('x-foo'));
}
public function testBatchesResults()
{
$requests = [
new Request('GET', 'http://foo.com/200'),
new Request('GET', 'http://foo.com/201'),
new Request('GET', 'http://foo.com/202'),
new Request('GET', 'http://foo.com/404'),
];
$fn = function (RequestInterface $request) {
return new Response(substr($request->getUri()->getPath(), 1));
};
$mock = new MockHandler([$fn, $fn, $fn, $fn]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$results = Pool::batch($client, $requests);
self::assertCount(4, $results);
self::assertSame([0, 1, 2, 3], array_keys($results));
self::assertSame(200, $results[0]->getStatusCode());
self::assertSame(201, $results[1]->getStatusCode());
self::assertSame(202, $results[2]->getStatusCode());
self::assertInstanceOf(ClientException::class, $results[3]);
}
public function testBatchesResultsWithCallbacks()
{
$requests = [
new Request('GET', 'http://foo.com/200'),
new Request('GET', 'http://foo.com/201')
];
$mock = new MockHandler([
function (RequestInterface $request) {
return new Response(substr($request->getUri()->getPath(), 1));
}
]);
$client = new Client(['handler' => $mock]);
$results = Pool::batch($client, $requests, [
'fulfilled' => function ($value) use (&$called) {
$called = true;
}
]);
self::assertCount(2, $results);
self::assertTrue($called);
}
public function testUsesYieldedKeyInFulfilledCallback()
{
$r1 = new Promise(function () use (&$r1) {
$r1->resolve(new Response());
});
$r2 = new Promise(function () use (&$r2) {
$r2->resolve(new Response());
});
$r3 = new Promise(function () use (&$r3) {
$r3->resolve(new Response());
});
$handler = new MockHandler([$r1, $r2, $r3]);
$c = new Client(['handler' => $handler]);
$keys = [];
$requests = [
'request_1' => new Request('GET', 'http://example.com'),
'request_2' => new Request('GET', 'http://example.com'),
'request_3' => new Request('GET', 'http://example.com'),
];
$p = new Pool($c, $requests, [
'pool_size' => 2,
'fulfilled' => function ($res, $index) use (&$keys) {
$keys[] = $index;
}
]);
$p->promise()->wait();
self::assertCount(3, $keys);
self::assertSame($keys, array_keys($requests));
}
private function getClient($total = 1)
{
$queue = [];
for ($i = 0; $i < $total; $i++) {
$queue[] = new Response();
}
$handler = new MockHandler($queue);
return new Client(['handler' => $handler]);
}
}

View File

@ -0,0 +1,155 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
class PrepareBodyMiddlewareTest extends TestCase
{
public function methodProvider()
{
$methods = ['GET', 'PUT', 'POST'];
$bodies = ['Test', ''];
foreach ($methods as $method) {
foreach ($bodies as $body) {
yield [$method, $body];
}
}
}
/**
* @dataProvider methodProvider
*/
public function testAddsContentLengthWhenMissingAndPossible($method, $body)
{
$h = new MockHandler([
function (RequestInterface $request) use ($body) {
$length = strlen($body);
if ($length > 0) {
self::assertEquals($length, $request->getHeaderLine('Content-Length'));
} else {
self::assertFalse($request->hasHeader('Content-Length'));
}
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request($method, 'http://www.google.com', [], $body), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testAddsTransferEncodingWhenNoContentLength()
{
$body = FnStream::decorate(Psr7\stream_for('foo'), [
'getSize' => function () {
return null;
}
]);
$h = new MockHandler([
function (RequestInterface $request) {
self::assertFalse($request->hasHeader('Content-Length'));
self::assertSame('chunked', $request->getHeaderLine('Transfer-Encoding'));
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $body), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testAddsContentTypeWhenMissingAndPossible()
{
$bd = Psr7\stream_for(fopen(__DIR__ . '/../composer.json', 'r'));
$h = new MockHandler([
function (RequestInterface $request) {
self::assertSame('application/json', $request->getHeaderLine('Content-Type'));
self::assertTrue($request->hasHeader('Content-Length'));
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $bd), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function expectProvider()
{
return [
[true, ['100-Continue']],
[false, []],
[10, ['100-Continue']],
[500000, []]
];
}
/**
* @dataProvider expectProvider
*/
public function testAddsExpect($value, $result)
{
$bd = Psr7\stream_for(fopen(__DIR__ . '/../composer.json', 'r'));
$h = new MockHandler([
function (RequestInterface $request) use ($result) {
self::assertSame($result, $request->getHeader('Expect'));
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $bd), [
'expect' => $value
]);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testIgnoresIfExpectIsPresent()
{
$bd = Psr7\stream_for(fopen(__DIR__ . '/../composer.json', 'r'));
$h = new MockHandler([
function (RequestInterface $request) {
self::assertSame(['Foo'], $request->getHeader('Expect'));
return new Response(200);
}
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(
new Request('PUT', 'http://www.google.com', ['Expect' => 'Foo'], $bd),
['expect' => true]
);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
}

View File

@ -0,0 +1,439 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RedirectMiddleware;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
/**
* @covers GuzzleHttp\RedirectMiddleware
*/
class RedirectMiddlewareTest extends TestCase
{
public function testIgnoresNonRedirects()
{
$response = new Response(200);
$stack = new HandlerStack(new MockHandler([$response]));
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, []);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testIgnoresWhenNoLocation()
{
$response = new Response(304);
$stack = new HandlerStack(new MockHandler([$response]));
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, []);
$response = $promise->wait();
self::assertSame(304, $response->getStatusCode());
}
public function testRedirectsWithAbsoluteUri()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2]
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('http://test.com', (string)$mock->getLastRequest()->getUri());
}
public function testRedirectsWithRelativeUri()
{
$mock = new MockHandler([
new Response(302, ['Location' => '/foo']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2]
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('http://example.com/foo', (string)$mock->getLastRequest()->getUri());
}
/**
* @expectedException \GuzzleHttp\Exception\TooManyRedirectsException
* @expectedExceptionMessage Will not follow more than 3 redirects
*/
public function testLimitsToMaxRedirects()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'http://test.com']),
new Response(302, ['Location' => 'http://test.com']),
new Response(303, ['Location' => 'http://test.com']),
new Response(304, ['Location' => 'http://test.com'])
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, ['allow_redirects' => ['max' => 3]]);
$promise->wait();
}
/**
* @expectedException \GuzzleHttp\Exception\BadResponseException
* @expectedExceptionMessage Redirect URI,
*/
public function testEnsuresProtocolIsValid()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'ftp://test.com'])
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$handler($request, ['allow_redirects' => ['max' => 3]])->wait();
}
public function testAddsRefererHeader()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true]
]);
$promise->wait();
self::assertSame(
'http://example.com?a=b',
$mock->getLastRequest()->getHeaderLine('Referer')
);
}
public function testAddsRefererHeaderButClearsUserInfo()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://foo:bar@example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true]
]);
$promise->wait();
self::assertSame(
'http://example.com?a=b',
$mock->getLastRequest()->getHeaderLine('Referer')
);
}
public function testAddsGuzzleRedirectHeader()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com']),
new Response(302, ['Location' => 'http://example.com/foo']),
new Response(302, ['Location' => 'http://example.com/bar']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['track_redirects' => true]
]);
$response = $promise->wait(true);
self::assertSame(
[
'http://example.com',
'http://example.com/foo',
'http://example.com/bar',
],
$response->getHeader(RedirectMiddleware::HISTORY_HEADER)
);
}
public function testAddsGuzzleRedirectStatusHeader()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'http://example.com']),
new Response(302, ['Location' => 'http://example.com/foo']),
new Response(301, ['Location' => 'http://example.com/bar']),
new Response(302, ['Location' => 'http://example.com/baz']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['track_redirects' => true]
]);
$response = $promise->wait(true);
self::assertSame(
[
'301',
'302',
'301',
'302',
],
$response->getHeader(RedirectMiddleware::STATUS_HISTORY_HEADER)
);
}
public function testDoesNotAddRefererWhenGoingFromHttpsToHttp()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'https://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true]
]);
$promise->wait();
self::assertFalse($mock->getLastRequest()->hasHeader('Referer'));
}
public function testInvokesOnRedirectForRedirects()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200)
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$call = false;
$promise = $handler($request, [
'allow_redirects' => [
'max' => 2,
'on_redirect' => function ($request, $response, $uri) use (&$call) {
self::assertSame(302, $response->getStatusCode());
self::assertSame('GET', $request->getMethod());
self::assertSame('http://test.com', (string) $uri);
$call = true;
}
]
]);
$promise->wait();
self::assertTrue($call);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossHost($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossPort($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com:81/']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossScheme($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com?a=b']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('https://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossSchemeSamePort($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com:80?a=b']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('https://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testNotRemoveCurlAuthorizationOptionsOnRedirect($auth)
{
if (!defined('\CURLOPT_HTTPAUTH') || !defined('\CURLOPT_USERPWD')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com/2']),
static function (RequestInterface $request, $options) {
self::assertTrue(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options does not contain expected CURLOPT_HTTPAUTH entry'
);
self::assertTrue(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options does not contain expected CURLOPT_USERPWD entry'
);
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
public function crossOriginRedirectProvider()
{
return [
['http://example.com/123', 'http://example.com/', false],
['http://example.com/123', 'http://example.com:80/', false],
['http://example.com:80/123', 'http://example.com/', false],
['http://example.com:80/123', 'http://example.com:80/', false],
['http://example.com/123', 'https://example.com/', true],
['http://example.com/123', 'http://www.example.com/', true],
['http://example.com/123', 'http://example.com:81/', true],
['http://example.com:80/123', 'http://example.com:81/', true],
['https://example.com/123', 'https://example.com/', false],
['https://example.com/123', 'https://example.com:443/', false],
['https://example.com:443/123', 'https://example.com/', false],
['https://example.com:443/123', 'https://example.com:443/', false],
['https://example.com/123', 'http://example.com/', true],
['https://example.com/123', 'https://www.example.com/', true],
['https://example.com/123', 'https://example.com:444/', true],
['https://example.com:443/123', 'https://example.com:444/', true],
];
}
/**
* @dataProvider crossOriginRedirectProvider
*/
public function testHeadersTreatmentOnRedirect($originalUri, $targetUri, $isCrossOrigin)
{
$mock = new MockHandler([
new Response(302, ['Location' => $targetUri]),
function (RequestInterface $request) use ($isCrossOrigin) {
self::assertSame(!$isCrossOrigin, $request->hasHeader('Authorization'));
self::assertSame(!$isCrossOrigin, $request->hasHeader('Cookie'));
return new Response(200);
}
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get($originalUri, ['auth' => ['testuser', 'testpass'], 'headers' => ['Cookie' => 'foo=bar']]);
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RetryMiddleware;
use PHPUnit\Framework\TestCase;
class RetryMiddlewareTest extends TestCase
{
public function testRetriesWhenDeciderReturnsTrue()
{
$delayCalls = 0;
$calls = [];
$decider = function ($retries, $request, $response, $error) use (&$calls) {
$calls[] = func_get_args();
return count($calls) < 3;
};
$delay = function ($retries, $response) use (&$delayCalls) {
$delayCalls++;
self::assertSame($retries, $delayCalls);
self::assertInstanceOf(Response::class, $response);
return 1;
};
$m = Middleware::retry($decider, $delay);
$h = new MockHandler([new Response(200), new Response(201), new Response(202)]);
$f = $m($h);
$c = new Client(['handler' => $f]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
$p->wait();
self::assertCount(3, $calls);
self::assertSame(2, $delayCalls);
self::assertSame(202, $p->wait()->getStatusCode());
}
public function testDoesNotRetryWhenDeciderReturnsFalse()
{
$decider = function () {
return false;
};
$m = Middleware::retry($decider);
$h = new MockHandler([new Response(200)]);
$c = new Client(['handler' => $m($h)]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
self::assertSame(200, $p->wait()->getStatusCode());
}
public function testCanRetryExceptions()
{
$calls = [];
$decider = function ($retries, $request, $response, $error) use (&$calls) {
$calls[] = func_get_args();
return $error instanceof \Exception;
};
$m = Middleware::retry($decider);
$h = new MockHandler([new \Exception(), new Response(201)]);
$c = new Client(['handler' => $m($h)]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
self::assertSame(201, $p->wait()->getStatusCode());
self::assertCount(2, $calls);
self::assertSame(0, $calls[0][0]);
self::assertNull($calls[0][2]);
self::assertInstanceOf('Exception', $calls[0][3]);
self::assertSame(1, $calls[1][0]);
self::assertInstanceOf(Response::class, $calls[1][2]);
self::assertNull($calls[1][3]);
}
public function testBackoffCalculateDelay()
{
self::assertSame(0, RetryMiddleware::exponentialDelay(0));
self::assertSame(1000, RetryMiddleware::exponentialDelay(1));
self::assertSame(2000, RetryMiddleware::exponentialDelay(2));
self::assertSame(4000, RetryMiddleware::exponentialDelay(3));
self::assertSame(8000, RetryMiddleware::exponentialDelay(4));
}
}

View File

@ -0,0 +1,174 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use Psr\Http\Message\ResponseInterface;
/**
* The Server class is used to control a scripted webserver using node.js that
* will respond to HTTP requests with queued responses.
*
* Queued responses will be served to requests using a FIFO order. All requests
* received by the server are stored on the node.js server and can be retrieved
* by calling {@see Server::received()}.
*
* Mock responses that don't require data to be transmitted over HTTP a great
* for testing. Mock response, however, cannot test the actual sending of an
* HTTP request using cURL. This test server allows the simulation of any
* number of HTTP request response transactions to test the actual sending of
* requests over the wire without having to leave an internal network.
*/
class Server
{
/** @var Client */
private static $client;
private static $started = false;
public static $url = 'http://127.0.0.1:8126/';
public static $port = 8126;
/**
* Flush the received requests from the server
* @throws \RuntimeException
*/
public static function flush()
{
return self::getClient()->request('DELETE', 'guzzle-server/requests');
}
/**
* Queue an array of responses or a single response on the server.
*
* Any currently queued responses will be overwritten. Subsequent requests
* on the server will return queued responses in FIFO order.
*
* @param array|ResponseInterface $responses A single or array of Responses
* to queue.
* @throws \Exception
*/
public static function enqueue($responses)
{
$data = [];
foreach ((array) $responses as $response) {
if (!($response instanceof ResponseInterface)) {
throw new \Exception('Invalid response given.');
}
$headers = array_map(function ($h) {
return implode(' ,', $h);
}, $response->getHeaders());
$data[] = [
'status' => (string) $response->getStatusCode(),
'reason' => $response->getReasonPhrase(),
'headers' => $headers,
'body' => base64_encode((string) $response->getBody())
];
}
self::getClient()->request('PUT', 'guzzle-server/responses', [
'json' => $data
]);
}
/**
* Get all of the received requests
*
* @return ResponseInterface[]
* @throws \RuntimeException
*/
public static function received()
{
if (!self::$started) {
return [];
}
$response = self::getClient()->request('GET', 'guzzle-server/requests');
$data = json_decode($response->getBody(), true);
return array_map(
function ($message) {
$uri = $message['uri'];
if (isset($message['query_string'])) {
$uri .= '?' . $message['query_string'];
}
$response = new Psr7\Request(
$message['http_method'],
$uri,
$message['headers'],
$message['body'],
$message['version']
);
return $response->withUri(
$response->getUri()
->withScheme('http')
->withHost($response->getHeaderLine('host'))
);
},
$data
);
}
/**
* Stop running the node.js server
*/
public static function stop()
{
if (self::$started) {
self::getClient()->request('DELETE', 'guzzle-server');
}
self::$started = false;
}
public static function wait($maxTries = 5)
{
$tries = 0;
while (!self::isListening() && ++$tries < $maxTries) {
usleep(100000);
}
if (!self::isListening()) {
throw new \RuntimeException('Unable to contact node.js server');
}
}
public static function start()
{
if (self::$started) {
return;
}
if (!self::isListening()) {
exec('node ' . __DIR__ . '/server.js '
. self::$port . ' >> /tmp/server.log 2>&1 &');
self::wait();
}
self::$started = true;
}
private static function isListening()
{
try {
self::getClient()->request('GET', 'guzzle-server/perf', [
'connect_timeout' => 5,
'timeout' => 5
]);
return true;
} catch (\Exception $e) {
return false;
}
}
private static function getClient()
{
if (!self::$client) {
self::$client = new Client([
'base_uri' => self::$url,
'sync' => true,
]);
}
return self::$client;
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Psr7;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
class TransferStatsTest extends TestCase
{
public function testHasData()
{
$request = new Psr7\Request('GET', 'http://foo.com');
$response = new Psr7\Response();
$stats = new TransferStats(
$request,
$response,
10.5,
null,
['foo' => 'bar']
);
self::assertSame($request, $stats->getRequest());
self::assertSame($response, $stats->getResponse());
self::assertTrue($stats->hasResponse());
self::assertSame(['foo' => 'bar'], $stats->getHandlerStats());
self::assertSame('bar', $stats->getHandlerStat('foo'));
self::assertSame($request->getUri(), $stats->getEffectiveUri());
self::assertEquals(10.5, $stats->getTransferTime());
self::assertNull($stats->getHandlerErrorData());
}
}

View File

@ -0,0 +1,202 @@
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\UriTemplate;
use PHPUnit\Framework\TestCase;
/**
* @covers GuzzleHttp\UriTemplate
*/
class UriTemplateTest extends TestCase
{
/**
* @return array
*/
public function templateProvider()
{
$params = [
'var' => 'value',
'hello' => 'Hello World!',
'empty' => '',
'path' => '/foo/bar',
'x' => '1024',
'y' => '768',
'null' => null,
'list' => ['red', 'green', 'blue'],
'keys' => [
"semi" => ';',
"dot" => '.',
"comma" => ','
],
'empty_keys' => [],
];
return array_map(function ($t) use ($params) {
$t[] = $params;
return $t;
}, [
['foo', 'foo'],
['{var}', 'value'],
['{hello}', 'Hello%20World%21'],
['{+var}', 'value'],
['{+hello}', 'Hello%20World!'],
['{+path}/here', '/foo/bar/here'],
['here?ref={+path}', 'here?ref=/foo/bar'],
['X{#var}', 'X#value'],
['X{#hello}', 'X#Hello%20World!'],
['map?{x,y}', 'map?1024,768'],
['{x,hello,y}', '1024,Hello%20World%21,768'],
['{+x,hello,y}', '1024,Hello%20World!,768'],
['{+path,x}/here', '/foo/bar,1024/here'],
['{#x,hello,y}', '#1024,Hello%20World!,768'],
['{#path,x}/here', '#/foo/bar,1024/here'],
['X{.var}', 'X.value'],
['X{.x,y}', 'X.1024.768'],
['{/var}', '/value'],
['{/var,x}/here', '/value/1024/here'],
['{;x,y}', ';x=1024;y=768'],
['{;x,y,empty}', ';x=1024;y=768;empty'],
['{?x,y}', '?x=1024&y=768'],
['{?x,y,empty}', '?x=1024&y=768&empty='],
['?fixed=yes{&x}', '?fixed=yes&x=1024'],
['{&x,y,empty}', '&x=1024&y=768&empty='],
['{var:3}', 'val'],
['{var:30}', 'value'],
['{list}', 'red,green,blue'],
['{list*}', 'red,green,blue'],
['{keys}', 'semi,%3B,dot,.,comma,%2C'],
['{keys*}', 'semi=%3B,dot=.,comma=%2C'],
['{+path:6}/here', '/foo/b/here'],
['{+list}', 'red,green,blue'],
['{+list*}', 'red,green,blue'],
['{+keys}', 'semi,;,dot,.,comma,,'],
['{+keys*}', 'semi=;,dot=.,comma=,'],
['{#path:6}/here', '#/foo/b/here'],
['{#list}', '#red,green,blue'],
['{#list*}', '#red,green,blue'],
['{#keys}', '#semi,;,dot,.,comma,,'],
['{#keys*}', '#semi=;,dot=.,comma=,'],
['X{.var:3}', 'X.val'],
['X{.list}', 'X.red,green,blue'],
['X{.list*}', 'X.red.green.blue'],
['X{.keys}', 'X.semi,%3B,dot,.,comma,%2C'],
['X{.keys*}', 'X.semi=%3B.dot=..comma=%2C'],
['{/var:1,var}', '/v/value'],
['{/list}', '/red,green,blue'],
['{/list*}', '/red/green/blue'],
['{/list*,path:4}', '/red/green/blue/%2Ffoo'],
['{/keys}', '/semi,%3B,dot,.,comma,%2C'],
['{/keys*}', '/semi=%3B/dot=./comma=%2C'],
['{;hello:5}', ';hello=Hello'],
['{;list}', ';list=red,green,blue'],
['{;list*}', ';list=red;list=green;list=blue'],
['{;keys}', ';keys=semi,%3B,dot,.,comma,%2C'],
['{;keys*}', ';semi=%3B;dot=.;comma=%2C'],
['{?var:3}', '?var=val'],
['{?list}', '?list=red,green,blue'],
['{?list*}', '?list=red&list=green&list=blue'],
['{?keys}', '?keys=semi,%3B,dot,.,comma,%2C'],
['{?keys*}', '?semi=%3B&dot=.&comma=%2C'],
['{&var:3}', '&var=val'],
['{&list}', '&list=red,green,blue'],
['{&list*}', '&list=red&list=green&list=blue'],
['{&keys}', '&keys=semi,%3B,dot,.,comma,%2C'],
['{&keys*}', '&semi=%3B&dot=.&comma=%2C'],
['{.null}', ''],
['{.null,var}', '.value'],
['X{.empty_keys*}', 'X'],
['X{.empty_keys}', 'X'],
// Test that missing expansions are skipped
['test{&missing*}', 'test'],
// Test that multiple expansions can be set
['http://{var}/{var:2}{?keys*}', 'http://value/va?semi=%3B&dot=.&comma=%2C'],
// Test more complex query string stuff
['http://www.test.com{+path}{?var,keys*}', 'http://www.test.com/foo/bar?var=value&semi=%3B&dot=.&comma=%2C']
]);
}
/**
* @dataProvider templateProvider
*/
public function testExpandsUriTemplates($template, $expansion, $params)
{
$uri = new UriTemplate();
self::assertSame($expansion, $uri->expand($template, $params));
}
public function expressionProvider()
{
return [
[
'{+var*}', [
'operator' => '+',
'values' => [
['modifier' => '*', 'value' => 'var']
]
],
],
[
'{?keys,var,val}', [
'operator' => '?',
'values' => [
['value' => 'keys', 'modifier' => ''],
['value' => 'var', 'modifier' => ''],
['value' => 'val', 'modifier' => '']
]
],
],
[
'{+x,hello,y}', [
'operator' => '+',
'values' => [
['value' => 'x', 'modifier' => ''],
['value' => 'hello', 'modifier' => ''],
['value' => 'y', 'modifier' => '']
]
]
]
];
}
/**
* @dataProvider expressionProvider
*/
public function testParsesExpressions($exp, $data)
{
$template = new UriTemplate();
// Access the config object
$class = new \ReflectionClass($template);
$method = $class->getMethod('parseExpression');
$method->setAccessible(true);
$exp = substr($exp, 1, -1);
self::assertSame($data, $method->invokeArgs($template, [$exp]));
}
/**
* @ticket https://github.com/guzzle/guzzle/issues/90
*/
public function testAllowsNestedArrayExpansion()
{
$template = new UriTemplate();
$result = $template->expand('http://example.com{+path}{/segments}{?query,data*,foo*}', [
'path' => '/foo/bar',
'segments' => ['one', 'two'],
'query' => 'test',
'data' => [
'more' => ['fun', 'ice cream']
],
'foo' => [
'baz' => [
'bar' => 'fizz',
'test' => 'buzz'
],
'bam' => 'boo'
]
]);
self::assertSame('http://example.com/foo/bar/one,two?query=test&more%5B0%5D=fun&more%5B1%5D=ice%20cream&baz%5Bbar%5D=fizz&baz%5Btest%5D=buzz&bam=boo', $result);
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace {
setlocale(LC_ALL, 'C');
}
namespace GuzzleHttp\Test {
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/Server.php';
use GuzzleHttp\Tests\Server;
Server::start();
register_shutdown_function(function () {
Server::stop();
});
}
// Override curl_setopt_array() and curl_multi_setopt() to get the last set curl options
namespace GuzzleHttp\Handler {
function curl_setopt_array($handle, array $options)
{
if (!empty($_SERVER['curl_test'])) {
$_SERVER['_curl'] = $options;
} else {
unset($_SERVER['_curl']);
}
return \curl_setopt_array($handle, $options);
}
function curl_multi_setopt($handle, $option, $value)
{
if (!empty($_SERVER['curl_test'])) {
$_SERVER['_curl_multi'][$option] = $value;
} else {
unset($_SERVER['_curl_multi']);
}
return \curl_multi_setopt($handle, $option, $value);
}
}

View File

@ -0,0 +1,139 @@
<?php
namespace GuzzleHttp\Test;
use GuzzleHttp;
use PHPUnit\Framework\TestCase;
class FunctionsTest extends TestCase
{
public function testExpandsTemplate()
{
self::assertSame(
'foo/123',
GuzzleHttp\uri_template('foo/{bar}', ['bar' => '123'])
);
}
public function noBodyProvider()
{
return [['get'], ['head'], ['delete']];
}
public function testProvidesDefaultUserAgent()
{
$ua = GuzzleHttp\default_user_agent();
self::assertRegExp('#^GuzzleHttp/.+ curl/.+ PHP/.+$#', $ua);
}
public function typeProvider()
{
return [
['foo', 'string(3) "foo"'],
[true, 'bool(true)'],
[false, 'bool(false)'],
[10, 'int(10)'],
[1.0, 'float(1)'],
[new StrClass(), 'object(GuzzleHttp\Test\StrClass)'],
[['foo'], 'array(1)']
];
}
/**
* @dataProvider typeProvider
*/
public function testDescribesType($input, $output)
{
self::assertSame($output, GuzzleHttp\describe_type($input));
}
public function testParsesHeadersFromLines()
{
$lines = ['Foo: bar', 'Foo: baz', 'Abc: 123', 'Def: a, b'];
self::assertSame([
'Foo' => ['bar', 'baz'],
'Abc' => ['123'],
'Def' => ['a, b'],
], GuzzleHttp\headers_from_lines($lines));
}
public function testParsesHeadersFromLinesWithMultipleLines()
{
$lines = ['Foo: bar', 'Foo: baz', 'Foo: 123'];
self::assertSame([
'Foo' => ['bar', 'baz', '123'],
], GuzzleHttp\headers_from_lines($lines));
}
public function testReturnsDebugResource()
{
self::assertInternalType('resource', GuzzleHttp\debug_resource());
}
public function testProvidesDefaultCaBundler()
{
self::assertFileExists(GuzzleHttp\default_ca_bundle());
}
public function noProxyProvider()
{
return [
['mit.edu', ['.mit.edu'], false],
['foo.mit.edu', ['.mit.edu'], true],
['mit.edu', ['mit.edu'], true],
['mit.edu', ['baz', 'mit.edu'], true],
['mit.edu', ['', '', 'mit.edu'], true],
['mit.edu', ['baz', '*'], true],
];
}
/**
* @dataProvider noproxyProvider
*/
public function testChecksNoProxyList($host, $list, $result)
{
self::assertSame(
$result,
\GuzzleHttp\is_host_in_noproxy($host, $list)
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEnsuresNoProxyCheckHostIsSet()
{
\GuzzleHttp\is_host_in_noproxy('', []);
}
public function testEncodesJson()
{
self::assertSame('true', \GuzzleHttp\json_encode(true));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testEncodesJsonAndThrowsOnError()
{
\GuzzleHttp\json_encode("\x99");
}
public function testDecodesJson()
{
self::assertTrue(\GuzzleHttp\json_decode('true'));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testDecodesJsonAndThrowsOnError()
{
\GuzzleHttp\json_decode('{{]]');
}
}
final class StrClass
{
public function __toString()
{
return 'foo';
}
}

View File

@ -0,0 +1,250 @@
/**
* Guzzle node.js test server to return queued responses to HTTP requests and
* expose a RESTful API for enqueueing responses and retrieving the requests
* that have been received.
*
* - Delete all requests that have been received:
* > DELETE /guzzle-server/requests
* > Host: 127.0.0.1:8126
*
* - Enqueue responses
* > PUT /guzzle-server/responses
* > Host: 127.0.0.1:8126
* >
* > [{'status': 200, 'reason': 'OK', 'headers': {}, 'body': '' }]
*
* - Get the received requests
* > GET /guzzle-server/requests
* > Host: 127.0.0.1:8126
*
* < HTTP/1.1 200 OK
* <
* < [{'http_method': 'GET', 'uri': '/', 'headers': {}, 'body': 'string'}]
*
* - Attempt access to the secure area
* > GET /secure/by-digest/qop-auth/guzzle-server/requests
* > Host: 127.0.0.1:8126
*
* < HTTP/1.1 401 Unauthorized
* < WWW-Authenticate: Digest realm="Digest Test", qop="auth", nonce="0796e98e1aeef43141fab2a66bf4521a", algorithm="MD5", stale="false"
* <
* < 401 Unauthorized
*
* - Shutdown the server
* > DELETE /guzzle-server
* > Host: 127.0.0.1:8126
*
* @package Guzzle PHP <http://www.guzzlephp.org>
* @license See the LICENSE file that was distributed with this source code.
*/
var http = require('http');
var url = require('url');
/**
* Guzzle node.js server
* @class
*/
var GuzzleServer = function(port, log) {
this.port = port;
this.log = log;
this.responses = [];
this.requests = [];
var that = this;
var md5 = function(input) {
var crypto = require('crypto');
var hasher = crypto.createHash('md5');
hasher.update(input);
return hasher.digest('hex');
};
/**
* Node.js HTTP server authentication module.
*
* It is only initialized on demand (by loadAuthentifier). This avoids
* requiring the dependency to http-auth on standard operations, and the
* performance hit at startup.
*/
var auth;
/**
* Provides authentication handlers (Basic, Digest).
*/
var loadAuthentifier = function(type, options) {
var typeId = type;
if (type == 'digest') {
typeId += '.'+(options && options.qop ? options.qop : 'none');
}
if (!loadAuthentifier[typeId]) {
if (!auth) {
try {
auth = require('http-auth');
} catch (e) {
if (e.code == 'MODULE_NOT_FOUND') {
return;
}
}
}
switch (type) {
case 'digest':
var digestParams = {
realm: 'Digest Test',
login: 'me',
password: 'test'
};
if (options && options.qop) {
digestParams.qop = options.qop;
}
loadAuthentifier[typeId] = auth.digest(digestParams, function(username, callback) {
callback(md5(digestParams.login + ':' + digestParams.realm + ':' + digestParams.password));
});
break
}
}
return loadAuthentifier[typeId];
};
var firewallRequest = function(request, req, res, requestHandlerCallback) {
var securedAreaUriParts = request.uri.match(/^\/secure\/by-(digest)(\/qop-([^\/]*))?(\/.*)$/);
if (securedAreaUriParts) {
var authentifier = loadAuthentifier(securedAreaUriParts[1], { qop: securedAreaUriParts[2] });
if (!authentifier) {
res.writeHead(501, 'HTTP authentication not implemented', { 'Content-Length': 0 });
res.end();
return;
}
authentifier.check(req, res, function(req, res) {
req.url = securedAreaUriParts[4];
requestHandlerCallback(request, req, res);
});
} else {
requestHandlerCallback(request, req, res);
}
};
var controlRequest = function(request, req, res) {
if (req.url == '/guzzle-server/perf') {
res.writeHead(200, 'OK', {'Content-Length': 16});
res.end('Body of response');
} else if (req.method == 'DELETE') {
if (req.url == '/guzzle-server/requests') {
// Clear the received requests
that.requests = [];
res.writeHead(200, 'OK', { 'Content-Length': 0 });
res.end();
if (that.log) {
console.log('Flushing requests');
}
} else if (req.url == '/guzzle-server') {
// Shutdown the server
res.writeHead(200, 'OK', { 'Content-Length': 0, 'Connection': 'close' });
res.end();
if (that.log) {
console.log('Shutting down');
}
that.server.close();
}
} else if (req.method == 'GET') {
if (req.url === '/guzzle-server/requests') {
if (that.log) {
console.log('Sending received requests');
}
// Get received requests
var body = JSON.stringify(that.requests);
res.writeHead(200, 'OK', { 'Content-Length': body.length });
res.end(body);
} else if (req.url == '/guzzle-server/read-timeout') {
if (that.log) {
console.log('Sleeping');
}
res.writeHead(200, 'OK');
res.write("sleeping 60 seconds ...\n");
setTimeout(function () {
res.end("slept 60 seconds\n");
}, 60*1000);
}
} else if (req.method == 'PUT' && req.url == '/guzzle-server/responses') {
if (that.log) {
console.log('Adding responses...');
}
if (!request.body) {
if (that.log) {
console.log('No response data was provided');
}
res.writeHead(400, 'NO RESPONSES IN REQUEST', { 'Content-Length': 0 });
} else {
that.responses = JSON.parse(request.body);
for (var i = 0; i < that.responses.length; i++) {
if (that.responses[i].body) {
that.responses[i].body = Buffer.from(that.responses[i].body, 'base64');
}
}
if (that.log) {
console.log(that.responses);
}
res.writeHead(200, 'OK', { 'Content-Length': 0 });
}
res.end();
}
};
var receivedRequest = function(request, req, res) {
if (req.url.indexOf('/guzzle-server') === 0) {
controlRequest(request, req, res);
} else if (req.url.indexOf('/guzzle-server') == -1 && !that.responses.length) {
res.writeHead(500);
res.end('No responses in queue');
} else {
if (that.log) {
console.log('Returning response from queue and adding request');
}
that.requests.push(request);
var response = that.responses.shift();
res.writeHead(response.status, response.reason, response.headers);
res.end(response.body);
}
};
this.start = function() {
that.server = http.createServer(function(req, res) {
var parts = url.parse(req.url, false);
var request = {
http_method: req.method,
scheme: parts.scheme,
uri: parts.pathname,
query_string: parts.query,
headers: req.headers,
version: req.httpVersion,
body: ''
};
// Receive each chunk of the request body
req.addListener('data', function(chunk) {
request.body += chunk;
});
// Called when the request completes
req.addListener('end', function() {
firewallRequest(request, req, res, receivedRequest);
});
});
that.server.listen(this.port, '127.0.0.1');
if (this.log) {
console.log('Server running at http://127.0.0.1:8126/');
}
};
};
// Get the port from the arguments
port = process.argv.length >= 3 ? process.argv[2] : 8126;
log = process.argv.length >= 4 ? process.argv[3] : false;
// Start the server
server = new GuzzleServer(port, log);
server.start();

View File

@ -1,5 +1,11 @@
# CHANGELOG
## 1.5.3 - 2023-05-21
### Changed
- Removed remaining usage of deprecated functions
## 1.5.2 - 2022-08-07
### Changed

View File

@ -46,11 +46,6 @@
"test": "vendor/bin/simple-phpunit",
"test-ci": "vendor/bin/simple-phpunit --coverage-text"
},
"extra": {
"branch-alias": {
"dev-master": "1.5-dev"
}
},
"config": {
"preferred-install": "dist",
"sort-packages": true

View File

@ -78,7 +78,7 @@ final class Each
$concurrency,
callable $onFulfilled = null
) {
return each_limit(
return self::ofLimit(
$iterable,
$concurrency,
$onFulfilled,

View File

@ -107,7 +107,7 @@ final class Utils
{
$results = [];
foreach ($promises as $key => $promise) {
$results[$key] = inspect($promise);
$results[$key] = self::inspect($promise);
}
return $results;

View File

@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

View File

@ -0,0 +1,7 @@
/tests export-ignore
.editorconfig export-ignore
.gitattributes export-ignore
.gitignore export-ignore
.travis.yml export-ignore
Makefile export-ignore
phpunit.xml.dist export-ignore

View File

@ -0,0 +1,2 @@
[*.yml]
indent_size = 2

View File

@ -0,0 +1,26 @@
language: php
matrix:
include:
- php: hhvm-3.24
dist: trusty
- php: 5.4
dist: trusty
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest"
- php: 5.4
dist: trusty
- php: 5.5.9
dist: trusty
env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest"
fast_finish: true
before_install:
- if [[ "$TRAVIS_PHP_VERSION" != "hhvm-3.24" ]]; then echo "xdebug.overload_var_dump = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi
- if [[ "$TRAVIS_PHP_VERSION" == "hhvm-3.24" ]]; then travis_retry composer require "phpunit/phpunit:^5.7.27" --dev --no-update -n; fi
install:
- if [[ "$TRAVIS_PHP_VERSION" != "nightly" ]]; then travis_retry composer update; fi
- if [[ "$TRAVIS_PHP_VERSION" == "nightly" ]]; then travis_retry composer update --ignore-platform-reqs; fi
script:
- make test

View File

@ -0,0 +1,29 @@
all: clean test
test:
vendor/bin/phpunit $(TEST)
coverage:
vendor/bin/phpunit --coverage-html=artifacts/coverage $(TEST)
view-coverage:
open artifacts/coverage/index.html
check-tag:
$(if $(TAG),,$(error TAG is not defined. Pass via "make tag TAG=4.2.1"))
tag: check-tag
@echo Tagging $(TAG)
chag update $(TAG)
git commit -a -m '$(TAG) release'
chag tag
@echo "Release has been created. Push using 'make release'"
@echo "Changes made in the release commit"
git diff HEAD~1 HEAD
release: check-tag
git push origin master
git push origin $(TAG)
clean:
rm -rf artifacts/*

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="true"
colors="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestsThatDoNotTestAnything="true"
bootstrap="vendor/autoload.php"
>
<testsuites>
<testsuite name="GuzzleHttp PSR7 Test Suite">
<directory>tests/</directory>
<exclude>tests/Integration</exclude>
</testsuite>
<testsuite name="Integration">
<directory>tests/Integration</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,213 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\AppendStream;
class AppendStreamTest extends BaseTest
{
public function testValidatesStreamsAreReadable()
{
$a = new AppendStream();
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isReadable'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('isReadable')
->will(self::returnValue(false));
$this->expectExceptionGuzzle('InvalidArgumentException', 'Each stream must be readable');
$a->addStream($s);
}
public function testValidatesSeekType()
{
$a = new AppendStream();
$this->expectExceptionGuzzle('RuntimeException', 'The AppendStream can only seek with SEEK_SET');
$a->seek(100, SEEK_CUR);
}
public function testTriesToRewindOnSeek()
{
$a = new AppendStream();
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isReadable', 'rewind', 'isSeekable'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('isReadable')
->will(self::returnValue(true));
$s->expects(self::once())
->method('isSeekable')
->will(self::returnValue(true));
$s->expects(self::once())
->method('rewind')
->will(self::throwException(new \RuntimeException()));
$a->addStream($s);
$this->expectExceptionGuzzle('RuntimeException', 'Unable to seek stream 0 of the AppendStream');
$a->seek(10);
}
public function testSeeksToPositionByReading()
{
$a = new AppendStream([
Psr7\Utils::streamFor('foo'),
Psr7\Utils::streamFor('bar'),
Psr7\Utils::streamFor('baz'),
]);
$a->seek(3);
self::assertSame(3, $a->tell());
self::assertSame('bar', $a->read(3));
$a->seek(6);
self::assertSame(6, $a->tell());
self::assertSame('baz', $a->read(3));
}
public function testDetachWithoutStreams()
{
$s = new AppendStream();
$s->detach();
self::assertSame(0, $s->getSize());
self::assertTrue($s->eof());
self::assertTrue($s->isReadable());
self::assertSame('', (string) $s);
self::assertTrue($s->isSeekable());
self::assertFalse($s->isWritable());
}
public function testDetachesEachStream()
{
$handle = fopen('php://temp', 'r');
$s1 = Psr7\Utils::streamFor($handle);
$s2 = Psr7\Utils::streamFor('bar');
$a = new AppendStream([$s1, $s2]);
$a->detach();
self::assertSame(0, $a->getSize());
self::assertTrue($a->eof());
self::assertTrue($a->isReadable());
self::assertSame('', (string) $a);
self::assertTrue($a->isSeekable());
self::assertFalse($a->isWritable());
self::assertNull($s1->detach());
$this->assertInternalTypeGuzzle('resource', $handle, 'resource is not closed when detaching');
fclose($handle);
}
public function testClosesEachStream()
{
$handle = fopen('php://temp', 'r');
$s1 = Psr7\Utils::streamFor($handle);
$s2 = Psr7\Utils::streamFor('bar');
$a = new AppendStream([$s1, $s2]);
$a->close();
self::assertSame(0, $a->getSize());
self::assertTrue($a->eof());
self::assertTrue($a->isReadable());
self::assertSame('', (string) $a);
self::assertTrue($a->isSeekable());
self::assertFalse($a->isWritable());
self::assertFalse(is_resource($handle));
}
public function testIsNotWritable()
{
$a = new AppendStream([Psr7\Utils::streamFor('foo')]);
self::assertFalse($a->isWritable());
self::assertTrue($a->isSeekable());
self::assertTrue($a->isReadable());
$this->expectExceptionGuzzle('RuntimeException', 'Cannot write to an AppendStream');
$a->write('foo');
}
public function testDoesNotNeedStreams()
{
$a = new AppendStream();
self::assertSame('', (string) $a);
}
public function testCanReadFromMultipleStreams()
{
$a = new AppendStream([
Psr7\Utils::streamFor('foo'),
Psr7\Utils::streamFor('bar'),
Psr7\Utils::streamFor('baz'),
]);
self::assertFalse($a->eof());
self::assertSame(0, $a->tell());
self::assertSame('foo', $a->read(3));
self::assertSame('bar', $a->read(3));
self::assertSame('baz', $a->read(3));
self::assertSame('', $a->read(1));
self::assertTrue($a->eof());
self::assertSame(9, $a->tell());
self::assertSame('foobarbaz', (string) $a);
}
public function testCanDetermineSizeFromMultipleStreams()
{
$a = new AppendStream([
Psr7\Utils::streamFor('foo'),
Psr7\Utils::streamFor('bar')
]);
self::assertSame(6, $a->getSize());
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isSeekable', 'isReadable'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('isSeekable')
->will(self::returnValue(null));
$s->expects(self::once())
->method('isReadable')
->will(self::returnValue(true));
$a->addStream($s);
self::assertNull($a->getSize());
}
public function testCatchesExceptionsWhenCastingToString()
{
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isSeekable', 'read', 'isReadable', 'eof'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('isSeekable')
->will(self::returnValue(true));
$s->expects(self::once())
->method('read')
->will(self::throwException(new \RuntimeException('foo')));
$s->expects(self::once())
->method('isReadable')
->will(self::returnValue(true));
$s->expects(self::any())
->method('eof')
->will(self::returnValue(false));
$a = new AppendStream([$s]);
self::assertFalse($a->eof());
self::assertSame('', (string) $a);
}
public function testReturnsEmptyMetadata()
{
$s = new AppendStream();
self::assertSame([], $s->getMetadata());
self::assertNull($s->getMetadata('foo'));
}
}

View File

@ -0,0 +1,139 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use PHPUnit\Framework\TestCase;
abstract class BaseTest extends TestCase
{
/**
* @param string $exception
* @param string|null $message
*/
public function expectExceptionGuzzle($exception, $message = null)
{
if (method_exists($this, 'setExpectedException')) {
$this->setExpectedException($exception, $message);
} else {
$this->expectException($exception);
if (null !== $message) {
$this->expectExceptionMessage($message);
}
}
}
public function expectWarningGuzzle()
{
if (method_exists($this, 'expectWarning')) {
$this->expectWarning();
} elseif (class_exists('PHPUnit\Framework\Error\Warning')) {
$this->expectExceptionGuzzle('PHPUnit\Framework\Error\Warning');
} else {
$this->expectExceptionGuzzle('PHPUnit_Framework_Error_Warning');
}
}
/**
* @param string $type
* @param mixed $input
*/
public function assertInternalTypeGuzzle($type, $input)
{
switch ($type) {
case 'array':
if (method_exists($this, 'assertIsArray')) {
self::assertIsArray($input);
} else {
self::assertInternalType('array', $input);
}
break;
case 'bool':
case 'boolean':
if (method_exists($this, 'assertIsBool')) {
self::assertIsBool($input);
} else {
self::assertInternalType('bool', $input);
}
break;
case 'double':
case 'float':
case 'real':
if (method_exists($this, 'assertIsFloat')) {
self::assertIsFloat($input);
} else {
self::assertInternalType('float', $input);
}
break;
case 'int':
case 'integer':
if (method_exists($this, 'assertIsInt')) {
self::assertIsInt($input);
} else {
self::assertInternalType('int', $input);
}
break;
case 'numeric':
if (method_exists($this, 'assertIsNumeric')) {
self::assertIsNumeric($input);
} else {
self::assertInternalType('numeric', $input);
}
break;
case 'object':
if (method_exists($this, 'assertIsObject')) {
self::assertIsObject($input);
} else {
self::assertInternalType('object', $input);
}
break;
case 'resource':
if (method_exists($this, 'assertIsResource')) {
self::assertIsResource($input);
} else {
self::assertInternalType('resource', $input);
}
break;
case 'string':
if (method_exists($this, 'assertIsString')) {
self::assertIsString($input);
} else {
self::assertInternalType('string', $input);
}
break;
case 'scalar':
if (method_exists($this, 'assertIsScalar')) {
self::assertIsScalar($input);
} else {
self::assertInternalType('scalar', $input);
}
break;
case 'callable':
if (method_exists($this, 'assertIsCallable')) {
self::assertIsCallable($input);
} else {
self::assertInternalType('callable', $input);
}
break;
case 'iterable':
if (method_exists($this, 'assertIsIterable')) {
self::assertIsIterable($input);
} else {
self::assertInternalType('iterable', $input);
}
break;
}
}
/**
* @param string $needle
* @param string $haystack
*/
public function assertStringContainsStringGuzzle($needle, $haystack)
{
if (method_exists($this, 'assertStringContainsString')) {
self::assertStringContainsString($needle, $haystack);
} else {
self::assertContains($needle, $haystack);
}
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\BufferStream;
class BufferStreamTest extends BaseTest
{
public function testHasMetadata()
{
$b = new BufferStream(10);
self::assertTrue($b->isReadable());
self::assertTrue($b->isWritable());
self::assertFalse($b->isSeekable());
self::assertSame(null, $b->getMetadata('foo'));
self::assertSame(10, $b->getMetadata('hwm'));
self::assertSame([], $b->getMetadata());
}
public function testRemovesReadDataFromBuffer()
{
$b = new BufferStream();
self::assertSame(3, $b->write('foo'));
self::assertSame(3, $b->getSize());
self::assertFalse($b->eof());
self::assertSame('foo', $b->read(10));
self::assertTrue($b->eof());
self::assertSame('', $b->read(10));
}
public function testCanCastToStringOrGetContents()
{
$b = new BufferStream();
$b->write('foo');
$b->write('baz');
self::assertSame('foo', $b->read(3));
$b->write('bar');
self::assertSame('bazbar', (string) $b);
$this->expectExceptionGuzzle('RuntimeException', 'Cannot determine the position of a BufferStream');
$b->tell();
}
public function testDetachClearsBuffer()
{
$b = new BufferStream();
$b->write('foo');
$b->detach();
self::assertTrue($b->eof());
self::assertSame(3, $b->write('abc'));
self::assertSame('abc', $b->read(10));
}
public function testExceedingHighwaterMarkReturnsFalseButStillBuffers()
{
$b = new BufferStream(5);
self::assertSame(3, $b->write('hi '));
self::assertFalse($b->write('hello'));
self::assertSame('hi hello', (string) $b);
self::assertSame(4, $b->write('test'));
}
}

View File

@ -0,0 +1,212 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\CachingStream;
use GuzzleHttp\Psr7\Stream;
/**
* @covers GuzzleHttp\Psr7\CachingStream
*/
class CachingStreamTest extends BaseTest
{
/** @var CachingStream */
private $body;
/** @var Stream */
private $decorated;
/**
* @before
*/
public function setUpTest()
{
$this->decorated = Psr7\Utils::streamFor('testing');
$this->body = new CachingStream($this->decorated);
}
/**
* @after
*/
public function tearDownTest()
{
$this->decorated->close();
$this->body->close();
}
public function testUsesRemoteSizeIfAvailable()
{
$body = Psr7\Utils::streamFor('test');
$caching = new CachingStream($body);
self::assertSame(4, $caching->getSize());
}
public function testUsesRemoteSizeIfNotAvailable()
{
$body = new Psr7\PumpStream(function () {
return 'a';
});
$caching = new CachingStream($body);
self::assertNull($caching->getSize());
}
public function testReadsUntilCachedToByte()
{
$this->body->seek(5);
self::assertSame('n', $this->body->read(1));
$this->body->seek(0);
self::assertSame('t', $this->body->read(1));
}
public function testCanSeekNearEndWithSeekEnd()
{
$baseStream = Psr7\Utils::streamFor(implode('', range('a', 'z')));
$cached = new CachingStream($baseStream);
$cached->seek(-1, SEEK_END);
self::assertSame(25, $baseStream->tell());
self::assertSame('z', $cached->read(1));
self::assertSame(26, $cached->getSize());
}
public function testCanSeekToEndWithSeekEnd()
{
$baseStream = Psr7\Utils::streamFor(implode('', range('a', 'z')));
$cached = new CachingStream($baseStream);
$cached->seek(0, SEEK_END);
self::assertSame(26, $baseStream->tell());
self::assertSame('', $cached->read(1));
self::assertSame(26, $cached->getSize());
}
public function testCanUseSeekEndWithUnknownSize()
{
$baseStream = Psr7\Utils::streamFor('testing');
$decorated = Psr7\FnStream::decorate($baseStream, [
'getSize' => function () {
return null;
}
]);
$cached = new CachingStream($decorated);
$cached->seek(-1, SEEK_END);
self::assertSame('g', $cached->read(1));
}
public function testRewindUsesSeek()
{
$a = Psr7\Utils::streamFor('foo');
$d = $this->getMockBuilder('GuzzleHttp\Psr7\CachingStream')
->setMethods(['seek'])
->setConstructorArgs([$a])
->getMock();
$d->expects(self::once())
->method('seek')
->with(0)
->will(self::returnValue(true));
$d->seek(0);
}
public function testCanSeekToReadBytes()
{
self::assertSame('te', $this->body->read(2));
$this->body->seek(0);
self::assertSame('test', $this->body->read(4));
self::assertSame(4, $this->body->tell());
$this->body->seek(2);
self::assertSame(2, $this->body->tell());
$this->body->seek(2, SEEK_CUR);
self::assertSame(4, $this->body->tell());
self::assertSame('ing', $this->body->read(3));
}
public function testCanSeekToReadBytesWithPartialBodyReturned()
{
$stream = fopen('php://temp', 'r+');
fwrite($stream, 'testing');
fseek($stream, 0);
$this->decorated = $this->getMockBuilder('\GuzzleHttp\Psr7\Stream')
->setConstructorArgs([$stream])
->setMethods(['read'])
->getMock();
$this->decorated->expects(self::exactly(2))
->method('read')
->willReturnCallback(function ($length) use ($stream) {
return fread($stream, 2);
});
$this->body = new CachingStream($this->decorated);
self::assertSame(0, $this->body->tell());
$this->body->seek(4, SEEK_SET);
self::assertSame(4, $this->body->tell());
$this->body->seek(0);
self::assertSame('test', $this->body->read(4));
}
public function testWritesToBufferStream()
{
$this->body->read(2);
$this->body->write('hi');
$this->body->seek(0);
self::assertSame('tehiing', (string) $this->body);
}
public function testSkipsOverwrittenBytes()
{
$decorated = Psr7\Utils::streamFor(
implode("\n", array_map(function ($n) {
return str_pad($n, 4, '0', STR_PAD_LEFT);
}, range(0, 25)))
);
$body = new CachingStream($decorated);
self::assertSame("0000\n", Psr7\Utils::readLine($body));
self::assertSame("0001\n", Psr7\Utils::readLine($body));
// Write over part of the body yet to be read, so skip some bytes
self::assertSame(5, $body->write("TEST\n"));
self::assertSame(5, Helpers::readObjectAttribute($body, 'skipReadBytes'));
// Read, which skips bytes, then reads
self::assertSame("0003\n", Psr7\Utils::readLine($body));
self::assertSame(0, Helpers::readObjectAttribute($body, 'skipReadBytes'));
self::assertSame("0004\n", Psr7\Utils::readLine($body));
self::assertSame("0005\n", Psr7\Utils::readLine($body));
// Overwrite part of the cached body (so don't skip any bytes)
$body->seek(5);
self::assertSame(5, $body->write("ABCD\n"));
self::assertSame(0, Helpers::readObjectAttribute($body, 'skipReadBytes'));
self::assertSame("TEST\n", Psr7\Utils::readLine($body));
self::assertSame("0003\n", Psr7\Utils::readLine($body));
self::assertSame("0004\n", Psr7\Utils::readLine($body));
self::assertSame("0005\n", Psr7\Utils::readLine($body));
self::assertSame("0006\n", Psr7\Utils::readLine($body));
self::assertSame(5, $body->write("1234\n"));
self::assertSame(5, Helpers::readObjectAttribute($body, 'skipReadBytes'));
// Seek to 0 and ensure the overwritten bit is replaced
$body->seek(0);
self::assertSame("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", $body->read(50));
// Ensure that casting it to a string does not include the bit that was overwritten
$this->assertStringContainsStringGuzzle("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", (string) $body);
}
public function testClosesBothStreams()
{
$s = fopen('php://temp', 'r');
$a = Psr7\Utils::streamFor($s);
$d = new CachingStream($a);
$d->close();
self::assertFalse(is_resource($s));
}
public function testEnsuresValidWhence()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
$this->body->seek(10, -123456);
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\BufferStream;
use GuzzleHttp\Psr7\DroppingStream;
class DroppingStreamTest extends BaseTest
{
public function testBeginsDroppingWhenSizeExceeded()
{
$stream = new BufferStream();
$drop = new DroppingStream($stream, 5);
self::assertSame(3, $drop->write('hel'));
self::assertSame(2, $drop->write('lo'));
self::assertSame(5, $drop->getSize());
self::assertSame('hello', $drop->read(5));
self::assertSame(0, $drop->getSize());
$drop->write('12345678910');
self::assertSame(5, $stream->getSize());
self::assertSame(5, $drop->getSize());
self::assertSame('12345', (string) $drop);
self::assertSame(0, $drop->getSize());
$drop->write('hello');
self::assertSame(0, $drop->write('test'));
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
/**
* @covers GuzzleHttp\Psr7\FnStream
*/
class FnStreamTest extends BaseTest
{
public function testThrowsWhenNotImplemented()
{
$this->expectExceptionGuzzle('BadMethodCallException', 'seek() is not implemented in the FnStream');
(new FnStream([]))->seek(1);
}
public function testProxiesToFunction()
{
$s = new FnStream([
'read' => function ($len) {
$this->assertSame(3, $len);
return 'foo';
}
]);
self::assertSame('foo', $s->read(3));
}
public function testCanCloseOnDestruct()
{
$called = false;
$s = new FnStream([
'close' => function () use (&$called) {
$called = true;
}
]);
unset($s);
self::assertTrue($called);
}
public function testDoesNotRequireClose()
{
$s = new FnStream([]);
unset($s);
self::assertTrue(true); // strict mode requires an assertion
}
public function testDecoratesStream()
{
$a = Psr7\Utils::streamFor('foo');
$b = FnStream::decorate($a, []);
self::assertSame(3, $b->getSize());
self::assertSame($b->isWritable(), true);
self::assertSame($b->isReadable(), true);
self::assertSame($b->isSeekable(), true);
self::assertSame($b->read(3), 'foo');
self::assertSame($b->tell(), 3);
self::assertSame($a->tell(), 3);
self::assertSame('', $a->read(1));
self::assertSame($b->eof(), true);
self::assertSame($a->eof(), true);
$b->seek(0);
self::assertSame('foo', (string) $b);
$b->seek(0);
self::assertSame('foo', $b->getContents());
self::assertSame($a->getMetadata(), $b->getMetadata());
$b->seek(0, SEEK_END);
$b->write('bar');
self::assertSame('foobar', (string) $b);
$this->assertInternalTypeGuzzle('resource', $b->detach());
$b->close();
}
public function testDecoratesWithCustomizations()
{
$called = false;
$a = Psr7\Utils::streamFor('foo');
$b = FnStream::decorate($a, [
'read' => function ($len) use (&$called, $a) {
$called = true;
return $a->read($len);
}
]);
self::assertSame('foo', $b->read(3));
self::assertTrue($called);
}
public function testDoNotAllowUnserialization()
{
$a = new FnStream([]);
$b = serialize($a);
$this->expectExceptionGuzzle('\LogicException', 'FnStream should never be unserialized');
unserialize($b);
}
}

Some files were not shown because too many files have changed in this diff Show More