modified file plugins

This commit is contained in:
2023-10-22 22:21:44 +00:00
committed by Gitium
parent c72a65abc1
commit 96c0ee892f
4817 changed files with 752216 additions and 0 deletions

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 @@
github: [Nyholm, GrahamCampbell]
tidelift: "packagist/guzzlehttp/psr7"

View File

@ -0,0 +1,14 @@
daysUntilStale: 120
daysUntilClose: 14
exemptLabels:
- lifecycle/keep-open
- lifecycle/ready-for-merge
# Label to use when marking an issue as stale
staleLabel: lifecycle/stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed after 2 weeks if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

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

View File

@ -0,0 +1,30 @@
name: CI
on:
pull_request:
jobs:
build:
name: Build
runs-on: ubuntu-22.04
strategy:
max-parallel: 10
matrix:
php: ['5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1']
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: 'none'
extensions: mbstring
- name: Checkout code
uses: actions/checkout@v3
- name: Install dependencies
run: composer update --no-interaction --no-progress
- name: Run tests
run: make test

View File

@ -0,0 +1,36 @@
name: Integration
on:
pull_request:
jobs:
build:
name: Test
runs-on: ubuntu-22.04
strategy:
max-parallel: 10
matrix:
php: ['7.2', '7.3', '7.4', '8.0', '8.1']
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
- name: Checkout code
uses: actions/checkout@v3
- name: Download dependencies
uses: ramsey/composer-install@v1
with:
composer-options: --no-interaction --optimize-autoloader
- name: Start server
run: php -S 127.0.0.1:10002 tests/Integration/server.php &
- name: Run tests
env:
TEST_SERVER: 127.0.0.1:10002
run: ./vendor/bin/phpunit --testsuite Integration

View File

@ -0,0 +1,29 @@
name: Static analysis
on:
pull_request:
jobs:
php-cs-fixer:
name: PHP-CS-Fixer
runs-on: ubuntu-22.04
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '7.4'
coverage: none
extensions: mbstring
- name: Download dependencies
run: composer update --no-interaction --no-progress
- name: Download PHP CS Fixer
run: composer require "friendsofphp/php-cs-fixer:2.18.4"
- name: Execute PHP CS Fixer
run: vendor/bin/php-cs-fixer fix --diff-format udiff --dry-run

View File

@ -0,0 +1,56 @@
<?php
$config = PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'concat_space' => ['spacing' => 'one'],
'declare_strict_types' => false,
'final_static_access' => true,
'fully_qualified_strict_types' => true,
'header_comment' => false,
'is_null' => ['use_yoda_style' => true],
'list_syntax' => ['syntax' => 'long'],
'lowercase_cast' => true,
'magic_method_casing' => true,
'modernize_types_casting' => true,
'multiline_comment_opening_closing' => true,
'no_alias_functions' => true,
'no_alternative_syntax' => true,
'no_blank_lines_after_phpdoc' => true,
'no_empty_comment' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_blank_lines' => true,
'no_leading_import_slash' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_unset_cast' => true,
'no_unused_imports' => true,
'no_whitespace_in_blank_line' => true,
'ordered_imports' => true,
'php_unit_ordered_covers' => true,
'php_unit_test_annotation' => ['style' => 'prefix'],
'php_unit_test_case_static_method_calls' => ['call_type' => 'self'],
'phpdoc_align' => ['align' => 'vertical'],
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_scalar' => true,
'phpdoc_separation' => true,
'phpdoc_single_line_var_spacing' => true,
'phpdoc_trim' => true,
'phpdoc_trim_consecutive_blank_line_separation' => true,
'phpdoc_types' => true,
'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'],
'phpdoc_var_without_name' => true,
'single_trait_insert_per_statement' => true,
'standardize_not_equals' => true,
])
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__.'/src')
->in(__DIR__.'/tests')
->name('*.php')
)
;
return $config;

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,324 @@
# Change Log
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
## 1.9.1 - 2023-04-17
### Fixed
- Fixed header validation issue
## 1.9.0 - 2022-06-20
### Added
- Added `UriComparator::isCrossOrigin` method
## 1.8.5 - 2022-03-20
### Fixed
- Correct header value validation
## 1.8.4 - 2022-03-20
### Fixed
- Validate header values properly
## 1.8.3 - 2021-10-05
### Fixed
- Return `null` in caching stream size if remote size is `null`
## 1.8.2 - 2021-04-26
### Fixed
- Handle possibly unset `url` in `stream_get_meta_data`
## 1.8.1 - 2021-03-21
### Fixed
- Issue parsing IPv6 URLs
- Issue modifying ServerRequest lost all its attributes
## 1.8.0 - 2021-03-21
### Added
- Locale independent URL parsing
- Most classes got a `@final` annotation to prepare for 2.0
### Fixed
- Issue when creating stream from `php://input` and curl-ext is not installed
- Broken `Utils::tryFopen()` on PHP 8
## 1.7.0 - 2020-09-30
### Added
- Replaced functions by static methods
### Fixed
- Converting a non-seekable stream to a string
- Handle multiple Set-Cookie correctly
- Ignore array keys in header values when merging
- Allow multibyte characters to be parsed in `Message:bodySummary()`
### Changed
- Restored partial HHVM 3 support
## [1.6.1] - 2019-07-02
### Fixed
- Accept null and bool header values again
## [1.6.0] - 2019-06-30
### Added
- Allowed version `^3.0` of `ralouphie/getallheaders` dependency (#244)
- Added MIME type for WEBP image format (#246)
- Added more validation of values according to PSR-7 and RFC standards, e.g. status code range (#250, #272)
### Changed
- Tests don't pass with HHVM 4.0, so HHVM support got dropped. Other libraries like composer have done the same. (#262)
- Accept port number 0 to be valid (#270)
### Fixed
- Fixed subsequent reads from `php://input` in ServerRequest (#247)
- Fixed readable/writable detection for certain stream modes (#248)
- Fixed encoding of special characters in the `userInfo` component of an URI (#253)
## [1.5.2] - 2018-12-04
### Fixed
- Check body size when getting the message summary
## [1.5.1] - 2018-12-04
### Fixed
- Get the summary of a body only if it is readable
## [1.5.0] - 2018-12-03
### Added
- Response first-line to response string exception (fixes #145)
- A test for #129 behavior
- `get_message_body_summary` function in order to get the message summary
- `3gp` and `mkv` mime types
### Changed
- Clarify exception message when stream is detached
### Deprecated
- Deprecated parsing folded header lines as per RFC 7230
### Fixed
- Fix `AppendStream::detach` to not close streams
- `InflateStream` preserves `isSeekable` attribute of the underlying stream
- `ServerRequest::getUriFromGlobals` to support URLs in query parameters
Several other fixes and improvements.
## [1.4.2] - 2017-03-20
### Fixed
- Reverted BC break to `Uri::resolve` and `Uri::removeDotSegments` by removing
calls to `trigger_error` when deprecated methods are invoked.
## [1.4.1] - 2017-02-27
### Added
- Rriggering of silenced deprecation warnings.
### Fixed
- Reverted BC break by reintroducing behavior to automagically fix a URI with a
relative path and an authority by adding a leading slash to the path. It's only
deprecated now.
## [1.4.0] - 2017-02-21
### Added
- Added common URI utility methods based on RFC 3986 (see documentation in the readme):
- `Uri::isDefaultPort`
- `Uri::isAbsolute`
- `Uri::isNetworkPathReference`
- `Uri::isAbsolutePathReference`
- `Uri::isRelativePathReference`
- `Uri::isSameDocumentReference`
- `Uri::composeComponents`
- `UriNormalizer::normalize`
- `UriNormalizer::isEquivalent`
- `UriResolver::relativize`
### Changed
- Ensure `ServerRequest::getUriFromGlobals` returns a URI in absolute form.
- Allow `parse_response` to parse a response without delimiting space and reason.
- Ensure each URI modification results in a valid URI according to PSR-7 discussions.
Invalid modifications will throw an exception instead of returning a wrong URI or
doing some magic.
- `(new Uri)->withPath('foo')->withHost('example.com')` will throw an exception
because the path of a URI with an authority must start with a slash "/" or be empty
- `(new Uri())->withScheme('http')` will return `'http://localhost'`
### Deprecated
- `Uri::resolve` in favor of `UriResolver::resolve`
- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments`
### Fixed
- `Stream::read` when length parameter <= 0.
- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory.
- `ServerRequest::getUriFromGlobals` when `Host` header contains port.
- Compatibility of URIs with `file` scheme and empty host.
## [1.3.1] - 2016-06-25
### Fixed
- `Uri::__toString` for network path references, e.g. `//example.org`.
- Missing lowercase normalization for host.
- Handling of URI components in case they are `'0'` in a lot of places,
e.g. as a user info password.
- `Uri::withAddedHeader` to correctly merge headers with different case.
- Trimming of header values in `Uri::withAddedHeader`. Header values may
be surrounded by whitespace which should be ignored according to RFC 7230
Section 3.2.4. This does not apply to header names.
- `Uri::withAddedHeader` with an array of header values.
- `Uri::resolve` when base path has no slash and handling of fragment.
- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the
key/value both in encoded as well as decoded form to those methods. This is
consistent with withPath, withQuery etc.
- `ServerRequest::withoutAttribute` when attribute value is null.
## [1.3.0] - 2016-04-13
### Added
- Remaining interfaces needed for full PSR7 compatibility
(ServerRequestInterface, UploadedFileInterface, etc.).
- Support for stream_for from scalars.
### Changed
- Can now extend Uri.
### Fixed
- A bug in validating request methods by making it more permissive.
## [1.2.3] - 2016-02-18
### Fixed
- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote
streams, which can sometimes return fewer bytes than requested with `fread`.
- Handling of gzipped responses with FNAME headers.
## [1.2.2] - 2016-01-22
### Added
- Support for URIs without any authority.
- Support for HTTP 451 'Unavailable For Legal Reasons.'
- Support for using '0' as a filename.
- Support for including non-standard ports in Host headers.
## [1.2.1] - 2015-11-02
### Changes
- Now supporting negative offsets when seeking to SEEK_END.
## [1.2.0] - 2015-08-15
### Changed
- Body as `"0"` is now properly added to a response.
- Now allowing forward seeking in CachingStream.
- Now properly parsing HTTP requests that contain proxy targets in
`parse_request`.
- functions.php is now conditionally required.
- user-info is no longer dropped when resolving URIs.
## [1.1.0] - 2015-06-24
### Changed
- URIs can now be relative.
- `multipart/form-data` headers are now overridden case-insensitively.
- URI paths no longer encode the following characters because they are allowed
in URIs: "(", ")", "*", "!", "'"
- A port is no longer added to a URI when the scheme is missing and no port is
present.
## 1.0.0 - 2015-05-19
Initial release.
Currently unsupported:
- `Psr\Http\Message\ServerRequestInterface`
- `Psr\Http\Message\UploadedFileInterface`
[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0
[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2
[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1
[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0
[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2
[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1
[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0
[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1
[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0
[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3
[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2
[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1
[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0
[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0

View File

@ -0,0 +1,26 @@
The MIT License (MIT)
Copyright (c) 2015 Michael Dowling <mtdowling@gmail.com>
Copyright (c) 2015 Márk Sági-Kazár <mark.sagikazar@gmail.com>
Copyright (c) 2015 Graham Campbell <hello@gjcampbell.co.uk>
Copyright (c) 2016 Tobias Schultze <webmaster@tubo-world.de>
Copyright (c) 2016 George Mponos <gmponos@gmail.com>
Copyright (c) 2018 Tobias Nyholm <tobias.nyholm@gmail.com>
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.

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,844 @@
# PSR-7 Message Implementation
This repository contains a full [PSR-7](https://www.php-fig.org/psr/psr-7/)
message implementation, several stream decorators, and some helpful
functionality like query string parsing.
[![Build Status](https://travis-ci.org/guzzle/psr7.svg?branch=master)](https://travis-ci.org/guzzle/psr7)
# Stream implementation
This package comes with a number of stream implementations and stream
decorators.
## AppendStream
`GuzzleHttp\Psr7\AppendStream`
Reads from multiple streams, one after the other.
```php
use GuzzleHttp\Psr7;
$a = Psr7\Utils::streamFor('abc, ');
$b = Psr7\Utils::streamFor('123.');
$composed = new Psr7\AppendStream([$a, $b]);
$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me'));
echo $composed; // abc, 123. Above all listen to me.
```
## BufferStream
`GuzzleHttp\Psr7\BufferStream`
Provides a buffer stream that can be written to fill a buffer, and read
from to remove bytes from the buffer.
This stream returns a "hwm" metadata value that tells upstream consumers
what the configured high water mark of the stream is, or the maximum
preferred size of the buffer.
```php
use GuzzleHttp\Psr7;
// When more than 1024 bytes are in the buffer, it will begin returning
// false to writes. This is an indication that writers should slow down.
$buffer = new Psr7\BufferStream(1024);
```
## CachingStream
The CachingStream is used to allow seeking over previously read bytes on
non-seekable streams. This can be useful when transferring a non-seekable
entity body fails due to needing to rewind the stream (for example, resulting
from a redirect). Data that is read from the remote stream will be buffered in
a PHP temp stream so that previously read bytes are cached first in memory,
then on disk.
```php
use GuzzleHttp\Psr7;
$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r'));
$stream = new Psr7\CachingStream($original);
$stream->read(1024);
echo $stream->tell();
// 1024
$stream->seek(0);
echo $stream->tell();
// 0
```
## DroppingStream
`GuzzleHttp\Psr7\DroppingStream`
Stream decorator that begins dropping data once the size of the underlying
stream becomes too full.
```php
use GuzzleHttp\Psr7;
// Create an empty stream
$stream = Psr7\Utils::streamFor();
// Start dropping data when the stream has more than 10 bytes
$dropping = new Psr7\DroppingStream($stream, 10);
$dropping->write('01234567890123456789');
echo $stream; // 0123456789
```
## FnStream
`GuzzleHttp\Psr7\FnStream`
Compose stream implementations based on a hash of functions.
Allows for easy testing and extension of a provided stream without needing
to create a concrete class for a simple extension point.
```php
use GuzzleHttp\Psr7;
$stream = Psr7\Utils::streamFor('hi');
$fnStream = Psr7\FnStream::decorate($stream, [
'rewind' => function () use ($stream) {
echo 'About to rewind - ';
$stream->rewind();
echo 'rewound!';
}
]);
$fnStream->rewind();
// Outputs: About to rewind - rewound!
```
## InflateStream
`GuzzleHttp\Psr7\InflateStream`
Uses PHP's zlib.inflate filter to inflate deflate or gzipped content.
This stream decorator skips the first 10 bytes of the given stream to remove
the gzip header, converts the provided stream to a PHP stream resource,
then appends the zlib.inflate filter. The stream is then converted back
to a Guzzle stream resource to be used as a Guzzle stream.
## LazyOpenStream
`GuzzleHttp\Psr7\LazyOpenStream`
Lazily reads or writes to a file that is opened only after an IO operation
take place on the stream.
```php
use GuzzleHttp\Psr7;
$stream = new Psr7\LazyOpenStream('/path/to/file', 'r');
// The file has not yet been opened...
echo $stream->read(10);
// The file is opened and read from only when needed.
```
## LimitStream
`GuzzleHttp\Psr7\LimitStream`
LimitStream can be used to read a subset or slice of an existing stream object.
This can be useful for breaking a large file into smaller pieces to be sent in
chunks (e.g. Amazon S3's multipart upload API).
```php
use GuzzleHttp\Psr7;
$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+'));
echo $original->getSize();
// >>> 1048576
// Limit the size of the body to 1024 bytes and start reading from byte 2048
$stream = new Psr7\LimitStream($original, 1024, 2048);
echo $stream->getSize();
// >>> 1024
echo $stream->tell();
// >>> 0
```
## MultipartStream
`GuzzleHttp\Psr7\MultipartStream`
Stream that when read returns bytes for a streaming multipart or
multipart/form-data stream.
## NoSeekStream
`GuzzleHttp\Psr7\NoSeekStream`
NoSeekStream wraps a stream and does not allow seeking.
```php
use GuzzleHttp\Psr7;
$original = Psr7\Utils::streamFor('foo');
$noSeek = new Psr7\NoSeekStream($original);
echo $noSeek->read(3);
// foo
var_export($noSeek->isSeekable());
// false
$noSeek->seek(0);
var_export($noSeek->read(3));
// NULL
```
## PumpStream
`GuzzleHttp\Psr7\PumpStream`
Provides a read only stream that pumps data from a PHP callable.
When invoking the provided callable, the PumpStream will pass the amount of
data requested to read to the callable. The callable can choose to ignore
this value and return fewer or more bytes than requested. Any extra data
returned by the provided callable is buffered internally until drained using
the read() function of the PumpStream. The provided callable MUST return
false when there is no more data to read.
## Implementing stream decorators
Creating a stream decorator is very easy thanks to the
`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that
implement `Psr\Http\Message\StreamInterface` by proxying to an underlying
stream. Just `use` the `StreamDecoratorTrait` and implement your custom
methods.
For example, let's say we wanted to call a specific function each time the last
byte is read from a stream. This could be implemented by overriding the
`read()` method.
```php
use Psr\Http\Message\StreamInterface;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
class EofCallbackStream implements StreamInterface
{
use StreamDecoratorTrait;
private $callback;
public function __construct(StreamInterface $stream, callable $cb)
{
$this->stream = $stream;
$this->callback = $cb;
}
public function read($length)
{
$result = $this->stream->read($length);
// Invoke the callback when EOF is hit.
if ($this->eof()) {
call_user_func($this->callback);
}
return $result;
}
}
```
This decorator could be added to any existing stream and used like so:
```php
use GuzzleHttp\Psr7;
$original = Psr7\Utils::streamFor('foo');
$eofStream = new EofCallbackStream($original, function () {
echo 'EOF!';
});
$eofStream->read(2);
$eofStream->read(1);
// echoes "EOF!"
$eofStream->seek(0);
$eofStream->read(3);
// echoes "EOF!"
```
## PHP StreamWrapper
You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a
PSR-7 stream as a PHP stream resource.
Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP
stream from a PSR-7 stream.
```php
use GuzzleHttp\Psr7\StreamWrapper;
$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!');
$resource = StreamWrapper::getResource($stream);
echo fread($resource, 6); // outputs hello!
```
# Static API
There are various static methods available under the `GuzzleHttp\Psr7` namespace.
## `GuzzleHttp\Psr7\Message::toString`
`public static function toString(MessageInterface $message): string`
Returns the string representation of an HTTP message.
```php
$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com');
echo GuzzleHttp\Psr7\Message::toString($request);
```
## `GuzzleHttp\Psr7\Message::bodySummary`
`public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null`
Get a short summary of the message body.
Will return `null` if the response is not printable.
## `GuzzleHttp\Psr7\Message::rewindBody`
`public static function rewindBody(MessageInterface $message): void`
Attempts to rewind a message body and throws an exception on failure.
The body of the message will only be rewound if a call to `tell()`
returns a value other than `0`.
## `GuzzleHttp\Psr7\Message::parseMessage`
`public static function parseMessage(string $message): array`
Parses an HTTP message into an associative array.
The array contains the "start-line" key containing the start line of
the message, "headers" key containing an associative array of header
array values, and a "body" key containing the body of the message.
## `GuzzleHttp\Psr7\Message::parseRequestUri`
`public static function parseRequestUri(string $path, array $headers): string`
Constructs a URI for an HTTP request message.
## `GuzzleHttp\Psr7\Message::parseRequest`
`public static function parseRequest(string $message): Request`
Parses a request message string into a request object.
## `GuzzleHttp\Psr7\Message::parseResponse`
`public static function parseResponse(string $message): Response`
Parses a response message string into a response object.
## `GuzzleHttp\Psr7\Header::parse`
`public static function parse(string|array $header): array`
Parse an array of header values containing ";" separated data into an
array of associative arrays representing the header key value pair data
of the header. When a parameter does not contain a value, but just
contains a key, this function will inject a key with a '' string value.
## `GuzzleHttp\Psr7\Header::normalize`
`public static function normalize(string|array $header): array`
Converts an array of header values that may contain comma separated
headers into an array of headers with no comma separated values.
## `GuzzleHttp\Psr7\Query::parse`
`public static function parse(string $str, int|bool $urlEncoding = true): array`
Parse a query string into an associative array.
If multiple values are found for the same key, the value of that key
value pair will become an array. This function does not parse nested
PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2`
will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`.
## `GuzzleHttp\Psr7\Query::build`
`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string`
Build a query string from an array of key value pairs.
This function can use the return value of `parse()` to build a query
string. This function does not modify the provided keys when an array is
encountered (like `http_build_query()` would).
## `GuzzleHttp\Psr7\Utils::caselessRemove`
`public static function caselessRemove(iterable<string> $keys, $keys, array $data): array`
Remove the items given by the keys, case insensitively from the data.
## `GuzzleHttp\Psr7\Utils::copyToStream`
`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void`
Copy the contents of a stream into another stream until the given number
of bytes have been read.
## `GuzzleHttp\Psr7\Utils::copyToString`
`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string`
Copy the contents of a stream into a string until the given number of
bytes have been read.
## `GuzzleHttp\Psr7\Utils::hash`
`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string`
Calculate a hash of a stream.
This method reads the entire stream to calculate a rolling hash, based on
PHP's `hash_init` functions.
## `GuzzleHttp\Psr7\Utils::modifyRequest`
`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface`
Clone and modify a request with the given changes.
This method is useful for reducing the number of clones needed to mutate
a message.
- method: (string) Changes the HTTP method.
- set_headers: (array) Sets the given headers.
- remove_headers: (array) Remove the given headers.
- body: (mixed) Sets the given body.
- uri: (UriInterface) Set the URI.
- query: (string) Set the query string value of the URI.
- version: (string) Set the protocol version.
## `GuzzleHttp\Psr7\Utils::readLine`
`public static function readLine(StreamInterface $stream, int $maxLength = null): string`
Read a line from the stream up to the maximum allowed buffer length.
## `GuzzleHttp\Psr7\Utils::streamFor`
`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface`
Create a new stream based on the input type.
Options is an associative array that can contain the following keys:
- metadata: Array of custom metadata.
- size: Size of the stream.
This method accepts the following `$resource` types:
- `Psr\Http\Message\StreamInterface`: Returns the value as-is.
- `string`: Creates a stream object that uses the given string as the contents.
- `resource`: Creates a stream object that wraps the given PHP stream resource.
- `Iterator`: If the provided value implements `Iterator`, then a read-only
stream object will be created that wraps the given iterable. Each time the
stream is read from, data from the iterator will fill a buffer and will be
continuously called until the buffer is equal to the requested read size.
Subsequent read calls will first read from the buffer and then call `next`
on the underlying iterator until it is exhausted.
- `object` with `__toString()`: If the object has the `__toString()` method,
the object will be cast to a string and then a stream will be returned that
uses the string value.
- `NULL`: When `null` is passed, an empty stream object is returned.
- `callable` When a callable is passed, a read-only stream object will be
created that invokes the given callable. The callable is invoked with the
number of suggested bytes to read. The callable can return any number of
bytes, but MUST return `false` when there is no more data to return. The
stream object that wraps the callable will invoke the callable until the
number of requested bytes are available. Any additional bytes will be
buffered and used in subsequent reads.
```php
$stream = GuzzleHttp\Psr7\Utils::streamFor('foo');
$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r'));
$generator = function ($bytes) {
for ($i = 0; $i < $bytes; $i++) {
yield ' ';
}
}
$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100));
```
## `GuzzleHttp\Psr7\Utils::tryFopen`
`public static function tryFopen(string $filename, string $mode): resource`
Safely opens a PHP stream resource using a filename.
When fopen fails, PHP normally raises a warning. This function adds an
error handler that checks for errors and throws an exception instead.
## `GuzzleHttp\Psr7\Utils::uriFor`
`public static function uriFor(string|UriInterface $uri): UriInterface`
Returns a UriInterface for the given value.
This function accepts a string or UriInterface and returns a
UriInterface for the given value. If the value is already a
UriInterface, it is returned as-is.
## `GuzzleHttp\Psr7\MimeType::fromFilename`
`public static function fromFilename(string $filename): string|null`
Determines the mimetype of a file by looking at its extension.
## `GuzzleHttp\Psr7\MimeType::fromExtension`
`public static function fromExtension(string $extension): string|null`
Maps a file extensions to a mimetype.
## Upgrading from Function API
The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API will be removed in 2.0.0. A migration table has been provided here for your convenience:
| Original Function | Replacement Method |
|----------------|----------------|
| `str` | `Message::toString` |
| `uri_for` | `Utils::uriFor` |
| `stream_for` | `Utils::streamFor` |
| `parse_header` | `Header::parse` |
| `normalize_header` | `Header::normalize` |
| `modify_request` | `Utils::modifyRequest` |
| `rewind_body` | `Message::rewindBody` |
| `try_fopen` | `Utils::tryFopen` |
| `copy_to_string` | `Utils::copyToString` |
| `copy_to_stream` | `Utils::copyToStream` |
| `hash` | `Utils::hash` |
| `readline` | `Utils::readLine` |
| `parse_request` | `Message::parseRequest` |
| `parse_response` | `Message::parseResponse` |
| `parse_query` | `Query::parse` |
| `build_query` | `Query::build` |
| `mimetype_from_filename` | `MimeType::fromFilename` |
| `mimetype_from_extension` | `MimeType::fromExtension` |
| `_parse_message` | `Message::parseMessage` |
| `_parse_request_uri` | `Message::parseRequestUri` |
| `get_message_body_summary` | `Message::bodySummary` |
| `_caseless_remove` | `Utils::caselessRemove` |
# Additional URI Methods
Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class,
this library also provides additional functionality when working with URIs as static methods.
## URI Types
An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference.
An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI,
the base URI. Relative references can be divided into several forms according to
[RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2):
- network-path references, e.g. `//example.com/path`
- absolute-path references, e.g. `/path`
- relative-path references, e.g. `subpath`
The following methods can be used to identify the type of the URI.
### `GuzzleHttp\Psr7\Uri::isAbsolute`
`public static function isAbsolute(UriInterface $uri): bool`
Whether the URI is absolute, i.e. it has a scheme.
### `GuzzleHttp\Psr7\Uri::isNetworkPathReference`
`public static function isNetworkPathReference(UriInterface $uri): bool`
Whether the URI is a network-path reference. A relative reference that begins with two slash characters is
termed an network-path reference.
### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference`
`public static function isAbsolutePathReference(UriInterface $uri): bool`
Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is
termed an absolute-path reference.
### `GuzzleHttp\Psr7\Uri::isRelativePathReference`
`public static function isRelativePathReference(UriInterface $uri): bool`
Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is
termed a relative-path reference.
### `GuzzleHttp\Psr7\Uri::isSameDocumentReference`
`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool`
Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its
fragment component, identical to the base URI. When no base URI is given, only an empty URI reference
(apart from its fragment) is considered a same-document reference.
## URI Components
Additional methods to work with URI components.
### `GuzzleHttp\Psr7\Uri::isDefaultPort`
`public static function isDefaultPort(UriInterface $uri): bool`
Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null
or the standard port. This method can be used independently of the implementation.
### `GuzzleHttp\Psr7\Uri::composeComponents`
`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string`
Composes a URI reference string from its various components according to
[RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called
manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`.
### `GuzzleHttp\Psr7\Uri::fromParts`
`public static function fromParts(array $parts): UriInterface`
Creates a URI from a hash of [`parse_url`](https://www.php.net/manual/en/function.parse-url.php) components.
### `GuzzleHttp\Psr7\Uri::withQueryValue`
`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface`
Creates a new URI with a specific query string value. Any existing query string values that exactly match the
provided key are removed and replaced with the given key value pair. A value of null will set the query string
key without a value, e.g. "key" instead of "key=value".
### `GuzzleHttp\Psr7\Uri::withQueryValues`
`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface`
Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an
associative array of key => value.
### `GuzzleHttp\Psr7\Uri::withoutQueryValue`
`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface`
Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the
provided key are removed.
## Cross-Origin Detection
`GuzzleHttp\Psr7\UriComparator` provides methods to determine if a modified URL should be considered cross-origin.
### `GuzzleHttp\Psr7\UriComparator::isCrossOrigin`
`public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool`
Determines if a modified URL should be considered cross-origin with respect to an original URL.
## Reference Resolution
`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according
to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers
do when resolving a link in a website based on the current request URI.
### `GuzzleHttp\Psr7\UriResolver::resolve`
`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface`
Converts the relative URI into a new URI that is resolved against the base URI.
### `GuzzleHttp\Psr7\UriResolver::removeDotSegments`
`public static function removeDotSegments(string $path): string`
Removes dot segments from a path and returns the new path according to
[RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4).
### `GuzzleHttp\Psr7\UriResolver::relativize`
`public static function relativize(UriInterface $base, UriInterface $target): UriInterface`
Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve():
```php
(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))
```
One use-case is to use the current request URI as base URI and then generate relative links in your documents
to reduce the document size or offer self-contained downloadable document archives.
```php
$base = new Uri('http://example.com/a/b/');
echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'.
echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'.
echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'.
```
## Normalization and Comparison
`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to
[RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6).
### `GuzzleHttp\Psr7\UriNormalizer::normalize`
`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface`
Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface.
This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask
of normalizations to apply. The following normalizations are available:
- `UriNormalizer::PRESERVING_NORMALIZATIONS`
Default normalizations which only include the ones that preserve semantics.
- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING`
All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.
Example: `http://example.org/a%c2%b1b``http://example.org/a%C2%B1b`
- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS`
Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of
ALPHA (%41%5A and %61%7A), DIGIT (%30%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should
not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved
characters by URI normalizers.
Example: `http://example.org/%7Eusern%61me/``http://example.org/~username/`
- `UriNormalizer::CONVERT_EMPTY_PATH`
Converts the empty path to "/" for http and https URIs.
Example: `http://example.org``http://example.org/`
- `UriNormalizer::REMOVE_DEFAULT_HOST`
Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host
"localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to
RFC 3986.
Example: `file://localhost/myfile``file:///myfile`
- `UriNormalizer::REMOVE_DEFAULT_PORT`
Removes the default port of the given URI scheme from the URI.
Example: `http://example.org:80/``http://example.org/`
- `UriNormalizer::REMOVE_DOT_SEGMENTS`
Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would
change the semantics of the URI reference.
Example: `http://example.org/../a/b/../c/./d.html``http://example.org/a/c/d.html`
- `UriNormalizer::REMOVE_DUPLICATE_SLASHES`
Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes
and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization
may change the semantics. Encoded slashes (%2F) are not removed.
Example: `http://example.org//foo///bar.html``http://example.org/foo/bar.html`
- `UriNormalizer::SORT_QUERY_PARAMETERS`
Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be
significant (this is not defined by the standard). So this normalization is not safe and may change the semantics
of the URI.
Example: `?lang=en&article=fred``?article=fred&lang=en`
### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent`
`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool`
Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given
`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent.
This of course assumes they will be resolved against the same base URI. If this is not the case, determination of
equivalence or difference of relative references does not mean anything.
## Version Guidance
| Version | Status | PHP Version |
|---------|----------------|------------------|
| 1.x | Security fixes | >=5.4,<8.1 |
| 2.x | Latest | ^7.2.5 \|\| ^8.0 |
## Security
If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information.
## License
Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.
## For Enterprise
Available as part of the Tidelift Subscription
The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

View File

@ -0,0 +1,71 @@
{
"name": "guzzlehttp/psr7",
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": ["request", "response", "message", "stream", "http", "uri", "url", "psr-7"],
"license": "MIT",
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "George Mponos",
"email": "gmponos@gmail.com",
"homepage": "https://github.com/gmponos"
},
{
"name": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/Nyholm"
},
{
"name": "Márk Sági-Kazár",
"email": "mark.sagikazar@gmail.com",
"homepage": "https://github.com/sagikazarmark"
},
{
"name": "Tobias Schultze",
"email": "webmaster@tubo-world.de",
"homepage": "https://github.com/Tobion"
}
],
"require": {
"php": ">=5.4.0",
"psr/http-message": "~1.0",
"ralouphie/getallheaders": "^2.0.5 || ^3.0.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.10",
"ext-zlib": "*"
},
"provide": {
"psr/http-message-implementation": "1.0"
},
"suggest": {
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
},
"files": ["src/functions_include.php"]
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Tests\\Psr7\\": "tests/"
}
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"bamarni/composer-bin-plugin": true
}
}
}

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,246 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Reads from multiple streams, one after the other.
*
* This is a read-only stream decorator.
*
* @final
*/
class AppendStream implements StreamInterface
{
/** @var StreamInterface[] Streams being decorated */
private $streams = [];
private $seekable = true;
private $current = 0;
private $pos = 0;
/**
* @param StreamInterface[] $streams Streams to decorate. Each stream must
* be readable.
*/
public function __construct(array $streams = [])
{
foreach ($streams as $stream) {
$this->addStream($stream);
}
}
public function __toString()
{
try {
$this->rewind();
return $this->getContents();
} catch (\Exception $e) {
return '';
}
}
/**
* Add a stream to the AppendStream
*
* @param StreamInterface $stream Stream to append. Must be readable.
*
* @throws \InvalidArgumentException if the stream is not readable
*/
public function addStream(StreamInterface $stream)
{
if (!$stream->isReadable()) {
throw new \InvalidArgumentException('Each stream must be readable');
}
// The stream is only seekable if all streams are seekable
if (!$stream->isSeekable()) {
$this->seekable = false;
}
$this->streams[] = $stream;
}
public function getContents()
{
return Utils::copyToString($this);
}
/**
* Closes each attached stream.
*
* {@inheritdoc}
*/
public function close()
{
$this->pos = $this->current = 0;
$this->seekable = true;
foreach ($this->streams as $stream) {
$stream->close();
}
$this->streams = [];
}
/**
* Detaches each attached stream.
*
* Returns null as it's not clear which underlying stream resource to return.
*
* {@inheritdoc}
*/
public function detach()
{
$this->pos = $this->current = 0;
$this->seekable = true;
foreach ($this->streams as $stream) {
$stream->detach();
}
$this->streams = [];
return null;
}
public function tell()
{
return $this->pos;
}
/**
* Tries to calculate the size by adding the size of each stream.
*
* If any of the streams do not return a valid number, then the size of the
* append stream cannot be determined and null is returned.
*
* {@inheritdoc}
*/
public function getSize()
{
$size = 0;
foreach ($this->streams as $stream) {
$s = $stream->getSize();
if ($s === null) {
return null;
}
$size += $s;
}
return $size;
}
public function eof()
{
return !$this->streams ||
($this->current >= count($this->streams) - 1 &&
$this->streams[$this->current]->eof());
}
public function rewind()
{
$this->seek(0);
}
/**
* Attempts to seek to the given position. Only supports SEEK_SET.
*
* {@inheritdoc}
*/
public function seek($offset, $whence = SEEK_SET)
{
if (!$this->seekable) {
throw new \RuntimeException('This AppendStream is not seekable');
} elseif ($whence !== SEEK_SET) {
throw new \RuntimeException('The AppendStream can only seek with SEEK_SET');
}
$this->pos = $this->current = 0;
// Rewind each stream
foreach ($this->streams as $i => $stream) {
try {
$stream->rewind();
} catch (\Exception $e) {
throw new \RuntimeException('Unable to seek stream '
. $i . ' of the AppendStream', 0, $e);
}
}
// Seek to the actual position by reading from each stream
while ($this->pos < $offset && !$this->eof()) {
$result = $this->read(min(8096, $offset - $this->pos));
if ($result === '') {
break;
}
}
}
/**
* Reads from all of the appended streams until the length is met or EOF.
*
* {@inheritdoc}
*/
public function read($length)
{
$buffer = '';
$total = count($this->streams) - 1;
$remaining = $length;
$progressToNext = false;
while ($remaining > 0) {
// Progress to the next stream if needed.
if ($progressToNext || $this->streams[$this->current]->eof()) {
$progressToNext = false;
if ($this->current === $total) {
break;
}
$this->current++;
}
$result = $this->streams[$this->current]->read($remaining);
// Using a loose comparison here to match on '', false, and null
if ($result == null) {
$progressToNext = true;
continue;
}
$buffer .= $result;
$remaining = $length - strlen($buffer);
}
$this->pos += strlen($buffer);
return $buffer;
}
public function isReadable()
{
return true;
}
public function isWritable()
{
return false;
}
public function isSeekable()
{
return $this->seekable;
}
public function write($string)
{
throw new \RuntimeException('Cannot write to an AppendStream');
}
public function getMetadata($key = null)
{
return $key ? null : [];
}
}

View File

@ -0,0 +1,142 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Provides a buffer stream that can be written to to fill a buffer, and read
* from to remove bytes from the buffer.
*
* This stream returns a "hwm" metadata value that tells upstream consumers
* what the configured high water mark of the stream is, or the maximum
* preferred size of the buffer.
*
* @final
*/
class BufferStream implements StreamInterface
{
private $hwm;
private $buffer = '';
/**
* @param int $hwm High water mark, representing the preferred maximum
* buffer size. If the size of the buffer exceeds the high
* water mark, then calls to write will continue to succeed
* but will return false to inform writers to slow down
* until the buffer has been drained by reading from it.
*/
public function __construct($hwm = 16384)
{
$this->hwm = $hwm;
}
public function __toString()
{
return $this->getContents();
}
public function getContents()
{
$buffer = $this->buffer;
$this->buffer = '';
return $buffer;
}
public function close()
{
$this->buffer = '';
}
public function detach()
{
$this->close();
return null;
}
public function getSize()
{
return strlen($this->buffer);
}
public function isReadable()
{
return true;
}
public function isWritable()
{
return true;
}
public function isSeekable()
{
return false;
}
public function rewind()
{
$this->seek(0);
}
public function seek($offset, $whence = SEEK_SET)
{
throw new \RuntimeException('Cannot seek a BufferStream');
}
public function eof()
{
return strlen($this->buffer) === 0;
}
public function tell()
{
throw new \RuntimeException('Cannot determine the position of a BufferStream');
}
/**
* Reads data from the buffer.
*/
public function read($length)
{
$currentLength = strlen($this->buffer);
if ($length >= $currentLength) {
// No need to slice the buffer because we don't have enough data.
$result = $this->buffer;
$this->buffer = '';
} else {
// Slice up the result to provide a subset of the buffer.
$result = substr($this->buffer, 0, $length);
$this->buffer = substr($this->buffer, $length);
}
return $result;
}
/**
* Writes data to the buffer.
*/
public function write($string)
{
$this->buffer .= $string;
// TODO: What should happen here?
if (strlen($this->buffer) >= $this->hwm) {
return false;
}
return strlen($string);
}
public function getMetadata($key = null)
{
if ($key == 'hwm') {
return $this->hwm;
}
return $key ? null : [];
}
}

View File

@ -0,0 +1,147 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Stream decorator that can cache previously read bytes from a sequentially
* read stream.
*
* @final
*/
class CachingStream implements StreamInterface
{
use StreamDecoratorTrait;
/** @var StreamInterface Stream being wrapped */
private $remoteStream;
/** @var int Number of bytes to skip reading due to a write on the buffer */
private $skipReadBytes = 0;
/**
* We will treat the buffer object as the body of the stream
*
* @param StreamInterface $stream Stream to cache. The cursor is assumed to be at the beginning of the stream.
* @param StreamInterface $target Optionally specify where data is cached
*/
public function __construct(
StreamInterface $stream,
StreamInterface $target = null
) {
$this->remoteStream = $stream;
$this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+'));
}
public function getSize()
{
$remoteSize = $this->remoteStream->getSize();
if (null === $remoteSize) {
return null;
}
return max($this->stream->getSize(), $remoteSize);
}
public function rewind()
{
$this->seek(0);
}
public function seek($offset, $whence = SEEK_SET)
{
if ($whence == SEEK_SET) {
$byte = $offset;
} elseif ($whence == SEEK_CUR) {
$byte = $offset + $this->tell();
} elseif ($whence == SEEK_END) {
$size = $this->remoteStream->getSize();
if ($size === null) {
$size = $this->cacheEntireStream();
}
$byte = $size + $offset;
} else {
throw new \InvalidArgumentException('Invalid whence');
}
$diff = $byte - $this->stream->getSize();
if ($diff > 0) {
// Read the remoteStream until we have read in at least the amount
// of bytes requested, or we reach the end of the file.
while ($diff > 0 && !$this->remoteStream->eof()) {
$this->read($diff);
$diff = $byte - $this->stream->getSize();
}
} else {
// We can just do a normal seek since we've already seen this byte.
$this->stream->seek($byte);
}
}
public function read($length)
{
// Perform a regular read on any previously read data from the buffer
$data = $this->stream->read($length);
$remaining = $length - strlen($data);
// More data was requested so read from the remote stream
if ($remaining) {
// If data was written to the buffer in a position that would have
// been filled from the remote stream, then we must skip bytes on
// the remote stream to emulate overwriting bytes from that
// position. This mimics the behavior of other PHP stream wrappers.
$remoteData = $this->remoteStream->read(
$remaining + $this->skipReadBytes
);
if ($this->skipReadBytes) {
$len = strlen($remoteData);
$remoteData = substr($remoteData, $this->skipReadBytes);
$this->skipReadBytes = max(0, $this->skipReadBytes - $len);
}
$data .= $remoteData;
$this->stream->write($remoteData);
}
return $data;
}
public function write($string)
{
// When appending to the end of the currently read stream, you'll want
// to skip bytes from being read from the remote stream to emulate
// other stream wrappers. Basically replacing bytes of data of a fixed
// length.
$overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell();
if ($overflow > 0) {
$this->skipReadBytes += $overflow;
}
return $this->stream->write($string);
}
public function eof()
{
return $this->stream->eof() && $this->remoteStream->eof();
}
/**
* Close both the remote stream and buffer stream
*/
public function close()
{
$this->remoteStream->close() && $this->stream->close();
}
private function cacheEntireStream()
{
$target = new FnStream(['write' => 'strlen']);
Utils::copyToStream($this, $target);
return $this->tell();
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Stream decorator that begins dropping data once the size of the underlying
* stream becomes too full.
*
* @final
*/
class DroppingStream implements StreamInterface
{
use StreamDecoratorTrait;
private $maxLength;
/**
* @param StreamInterface $stream Underlying stream to decorate.
* @param int $maxLength Maximum size before dropping data.
*/
public function __construct(StreamInterface $stream, $maxLength)
{
$this->stream = $stream;
$this->maxLength = $maxLength;
}
public function write($string)
{
$diff = $this->maxLength - $this->stream->getSize();
// Begin returning 0 when the underlying stream is too large.
if ($diff <= 0) {
return 0;
}
// Write the stream or a subset of the stream if needed.
if (strlen($string) < $diff) {
return $this->stream->write($string);
}
return $this->stream->write(substr($string, 0, $diff));
}
}

View File

@ -0,0 +1,163 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Compose stream implementations based on a hash of functions.
*
* Allows for easy testing and extension of a provided stream without needing
* to create a concrete class for a simple extension point.
*
* @final
*/
class FnStream implements StreamInterface
{
/** @var array */
private $methods;
/** @var array Methods that must be implemented in the given array */
private static $slots = ['__toString', 'close', 'detach', 'rewind',
'getSize', 'tell', 'eof', 'isSeekable', 'seek', 'isWritable', 'write',
'isReadable', 'read', 'getContents', 'getMetadata'];
/**
* @param array $methods Hash of method name to a callable.
*/
public function __construct(array $methods)
{
$this->methods = $methods;
// Create the functions on the class
foreach ($methods as $name => $fn) {
$this->{'_fn_' . $name} = $fn;
}
}
/**
* Lazily determine which methods are not implemented.
*
* @throws \BadMethodCallException
*/
public function __get($name)
{
throw new \BadMethodCallException(str_replace('_fn_', '', $name)
. '() is not implemented in the FnStream');
}
/**
* The close method is called on the underlying stream only if possible.
*/
public function __destruct()
{
if (isset($this->_fn_close)) {
call_user_func($this->_fn_close);
}
}
/**
* An unserialize would allow the __destruct to run when the unserialized value goes out of scope.
*
* @throws \LogicException
*/
public function __wakeup()
{
throw new \LogicException('FnStream should never be unserialized');
}
/**
* Adds custom functionality to an underlying stream by intercepting
* specific method calls.
*
* @param StreamInterface $stream Stream to decorate
* @param array $methods Hash of method name to a closure
*
* @return FnStream
*/
public static function decorate(StreamInterface $stream, array $methods)
{
// If any of the required methods were not provided, then simply
// proxy to the decorated stream.
foreach (array_diff(self::$slots, array_keys($methods)) as $diff) {
$methods[$diff] = [$stream, $diff];
}
return new self($methods);
}
public function __toString()
{
return call_user_func($this->_fn___toString);
}
public function close()
{
return call_user_func($this->_fn_close);
}
public function detach()
{
return call_user_func($this->_fn_detach);
}
public function getSize()
{
return call_user_func($this->_fn_getSize);
}
public function tell()
{
return call_user_func($this->_fn_tell);
}
public function eof()
{
return call_user_func($this->_fn_eof);
}
public function isSeekable()
{
return call_user_func($this->_fn_isSeekable);
}
public function rewind()
{
call_user_func($this->_fn_rewind);
}
public function seek($offset, $whence = SEEK_SET)
{
call_user_func($this->_fn_seek, $offset, $whence);
}
public function isWritable()
{
return call_user_func($this->_fn_isWritable);
}
public function write($string)
{
return call_user_func($this->_fn_write, $string);
}
public function isReadable()
{
return call_user_func($this->_fn_isReadable);
}
public function read($length)
{
return call_user_func($this->_fn_read, $length);
}
public function getContents()
{
return call_user_func($this->_fn_getContents);
}
public function getMetadata($key = null)
{
return call_user_func($this->_fn_getMetadata, $key);
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace GuzzleHttp\Psr7;
final class Header
{
/**
* Parse an array of header values containing ";" separated data into an
* array of associative arrays representing the header key value pair data
* of the header. When a parameter does not contain a value, but just
* contains a key, this function will inject a key with a '' string value.
*
* @param string|array $header Header to parse into components.
*
* @return array Returns the parsed header values.
*/
public static function parse($header)
{
static $trimmed = "\"' \n\t\r";
$params = $matches = [];
foreach (self::normalize($header) as $val) {
$part = [];
foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) {
if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) {
$m = $matches[0];
if (isset($m[1])) {
$part[trim($m[0], $trimmed)] = trim($m[1], $trimmed);
} else {
$part[] = trim($m[0], $trimmed);
}
}
}
if ($part) {
$params[] = $part;
}
}
return $params;
}
/**
* Converts an array of header values that may contain comma separated
* headers into an array of headers with no comma separated values.
*
* @param string|array $header Header to normalize.
*
* @return array Returns the normalized header field values.
*/
public static function normalize($header)
{
if (!is_array($header)) {
return array_map('trim', explode(',', $header));
}
$result = [];
foreach ($header as $value) {
foreach ((array) $value as $v) {
if (strpos($v, ',') === false) {
$result[] = $v;
continue;
}
foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) {
$result[] = trim($vv);
}
}
}
return $result;
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Uses PHP's zlib.inflate filter to inflate deflate or gzipped content.
*
* This stream decorator skips the first 10 bytes of the given stream to remove
* the gzip header, converts the provided stream to a PHP stream resource,
* then appends the zlib.inflate filter. The stream is then converted back
* to a Guzzle stream resource to be used as a Guzzle stream.
*
* @link http://tools.ietf.org/html/rfc1952
* @link http://php.net/manual/en/filters.compression.php
*
* @final
*/
class InflateStream implements StreamInterface
{
use StreamDecoratorTrait;
public function __construct(StreamInterface $stream)
{
// read the first 10 bytes, ie. gzip header
$header = $stream->read(10);
$filenameHeaderLength = $this->getLengthOfPossibleFilenameHeader($stream, $header);
// Skip the header, that is 10 + length of filename + 1 (nil) bytes
$stream = new LimitStream($stream, -1, 10 + $filenameHeaderLength);
$resource = StreamWrapper::getResource($stream);
stream_filter_append($resource, 'zlib.inflate', STREAM_FILTER_READ);
$this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource));
}
/**
* @param StreamInterface $stream
* @param $header
*
* @return int
*/
private function getLengthOfPossibleFilenameHeader(StreamInterface $stream, $header)
{
$filename_header_length = 0;
if (substr(bin2hex($header), 6, 2) === '08') {
// we have a filename, read until nil
$filename_header_length = 1;
while ($stream->read(1) !== chr(0)) {
$filename_header_length++;
}
}
return $filename_header_length;
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Lazily reads or writes to a file that is opened only after an IO operation
* take place on the stream.
*
* @final
*/
class LazyOpenStream implements StreamInterface
{
use StreamDecoratorTrait;
/** @var string File to open */
private $filename;
/** @var string */
private $mode;
/**
* @param string $filename File to lazily open
* @param string $mode fopen mode to use when opening the stream
*/
public function __construct($filename, $mode)
{
$this->filename = $filename;
$this->mode = $mode;
}
/**
* Creates the underlying stream lazily when required.
*
* @return StreamInterface
*/
protected function createStream()
{
return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode));
}
}

View File

@ -0,0 +1,157 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Decorator used to return only a subset of a stream.
*
* @final
*/
class LimitStream implements StreamInterface
{
use StreamDecoratorTrait;
/** @var int Offset to start reading from */
private $offset;
/** @var int Limit the number of bytes that can be read */
private $limit;
/**
* @param StreamInterface $stream Stream to wrap
* @param int $limit Total number of bytes to allow to be read
* from the stream. Pass -1 for no limit.
* @param int $offset Position to seek to before reading (only
* works on seekable streams).
*/
public function __construct(
StreamInterface $stream,
$limit = -1,
$offset = 0
) {
$this->stream = $stream;
$this->setLimit($limit);
$this->setOffset($offset);
}
public function eof()
{
// Always return true if the underlying stream is EOF
if ($this->stream->eof()) {
return true;
}
// No limit and the underlying stream is not at EOF
if ($this->limit == -1) {
return false;
}
return $this->stream->tell() >= $this->offset + $this->limit;
}
/**
* Returns the size of the limited subset of data
* {@inheritdoc}
*/
public function getSize()
{
if (null === ($length = $this->stream->getSize())) {
return null;
} elseif ($this->limit == -1) {
return $length - $this->offset;
} else {
return min($this->limit, $length - $this->offset);
}
}
/**
* Allow for a bounded seek on the read limited stream
* {@inheritdoc}
*/
public function seek($offset, $whence = SEEK_SET)
{
if ($whence !== SEEK_SET || $offset < 0) {
throw new \RuntimeException(sprintf(
'Cannot seek to offset %s with whence %s',
$offset,
$whence
));
}
$offset += $this->offset;
if ($this->limit !== -1) {
if ($offset > $this->offset + $this->limit) {
$offset = $this->offset + $this->limit;
}
}
$this->stream->seek($offset);
}
/**
* Give a relative tell()
* {@inheritdoc}
*/
public function tell()
{
return $this->stream->tell() - $this->offset;
}
/**
* Set the offset to start limiting from
*
* @param int $offset Offset to seek to and begin byte limiting from
*
* @throws \RuntimeException if the stream cannot be seeked.
*/
public function setOffset($offset)
{
$current = $this->stream->tell();
if ($current !== $offset) {
// If the stream cannot seek to the offset position, then read to it
if ($this->stream->isSeekable()) {
$this->stream->seek($offset);
} elseif ($current > $offset) {
throw new \RuntimeException("Could not seek to stream offset $offset");
} else {
$this->stream->read($offset - $current);
}
}
$this->offset = $offset;
}
/**
* Set the limit of bytes that the decorator allows to be read from the
* stream.
*
* @param int $limit Number of bytes to allow to be read from the stream.
* Use -1 for no limit.
*/
public function setLimit($limit)
{
$this->limit = $limit;
}
public function read($length)
{
if ($this->limit == -1) {
return $this->stream->read($length);
}
// Check if the current position is less than the total allowed
// bytes + original offset
$remaining = ($this->offset + $this->limit) - $this->stream->tell();
if ($remaining > 0) {
// Only return the amount of requested data, ensuring that the byte
// limit is not exceeded
return $this->stream->read(min($remaining, $length));
}
return '';
}
}

View File

@ -0,0 +1,252 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
final class Message
{
/**
* Returns the string representation of an HTTP message.
*
* @param MessageInterface $message Message to convert to a string.
*
* @return string
*/
public static function toString(MessageInterface $message)
{
if ($message instanceof RequestInterface) {
$msg = trim($message->getMethod() . ' '
. $message->getRequestTarget())
. ' HTTP/' . $message->getProtocolVersion();
if (!$message->hasHeader('host')) {
$msg .= "\r\nHost: " . $message->getUri()->getHost();
}
} elseif ($message instanceof ResponseInterface) {
$msg = 'HTTP/' . $message->getProtocolVersion() . ' '
. $message->getStatusCode() . ' '
. $message->getReasonPhrase();
} else {
throw new \InvalidArgumentException('Unknown message type');
}
foreach ($message->getHeaders() as $name => $values) {
if (strtolower($name) === 'set-cookie') {
foreach ($values as $value) {
$msg .= "\r\n{$name}: " . $value;
}
} else {
$msg .= "\r\n{$name}: " . implode(', ', $values);
}
}
return "{$msg}\r\n\r\n" . $message->getBody();
}
/**
* Get a short summary of the message body.
*
* Will return `null` if the response is not printable.
*
* @param MessageInterface $message The message to get the body summary
* @param int $truncateAt The maximum allowed size of the summary
*
* @return string|null
*/
public static function bodySummary(MessageInterface $message, $truncateAt = 120)
{
$body = $message->getBody();
if (!$body->isSeekable() || !$body->isReadable()) {
return null;
}
$size = $body->getSize();
if ($size === 0) {
return null;
}
$summary = $body->read($truncateAt);
$body->rewind();
if ($size > $truncateAt) {
$summary .= ' (truncated...)';
}
// Matches any printable character, including unicode characters:
// letters, marks, numbers, punctuation, spacing, and separators.
if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary)) {
return null;
}
return $summary;
}
/**
* Attempts to rewind a message body and throws an exception on failure.
*
* The body of the message will only be rewound if a call to `tell()`
* returns a value other than `0`.
*
* @param MessageInterface $message Message to rewind
*
* @throws \RuntimeException
*/
public static function rewindBody(MessageInterface $message)
{
$body = $message->getBody();
if ($body->tell()) {
$body->rewind();
}
}
/**
* Parses an HTTP message into an associative array.
*
* The array contains the "start-line" key containing the start line of
* the message, "headers" key containing an associative array of header
* array values, and a "body" key containing the body of the message.
*
* @param string $message HTTP request or response to parse.
*
* @return array
*/
public static function parseMessage($message)
{
if (!$message) {
throw new \InvalidArgumentException('Invalid message');
}
$message = ltrim($message, "\r\n");
$messageParts = preg_split("/\r?\n\r?\n/", $message, 2);
if ($messageParts === false || count($messageParts) !== 2) {
throw new \InvalidArgumentException('Invalid message: Missing header delimiter');
}
list($rawHeaders, $body) = $messageParts;
$rawHeaders .= "\r\n"; // Put back the delimiter we split previously
$headerParts = preg_split("/\r?\n/", $rawHeaders, 2);
if ($headerParts === false || count($headerParts) !== 2) {
throw new \InvalidArgumentException('Invalid message: Missing status line');
}
list($startLine, $rawHeaders) = $headerParts;
if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') {
// Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0
$rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders);
}
/** @var array[] $headerLines */
$count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER);
// If these aren't the same, then one line didn't match and there's an invalid header.
if ($count !== substr_count($rawHeaders, "\n")) {
// Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4
if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) {
throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
}
throw new \InvalidArgumentException('Invalid header syntax');
}
$headers = [];
foreach ($headerLines as $headerLine) {
$headers[$headerLine[1]][] = $headerLine[2];
}
return [
'start-line' => $startLine,
'headers' => $headers,
'body' => $body,
];
}
/**
* Constructs a URI for an HTTP request message.
*
* @param string $path Path from the start-line
* @param array $headers Array of headers (each value an array).
*
* @return string
*/
public static function parseRequestUri($path, array $headers)
{
$hostKey = array_filter(array_keys($headers), function ($k) {
return strtolower($k) === 'host';
});
// If no host is found, then a full URI cannot be constructed.
if (!$hostKey) {
return $path;
}
$host = $headers[reset($hostKey)][0];
$scheme = substr($host, -4) === ':443' ? 'https' : 'http';
return $scheme . '://' . $host . '/' . ltrim($path, '/');
}
/**
* Parses a request message string into a request object.
*
* @param string $message Request message string.
*
* @return Request
*/
public static function parseRequest($message)
{
$data = self::parseMessage($message);
$matches = [];
if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
throw new \InvalidArgumentException('Invalid request string');
}
$parts = explode(' ', $data['start-line'], 3);
$version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
$request = new Request(
$parts[0],
$matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1],
$data['headers'],
$data['body'],
$version
);
return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
}
/**
* Parses a response message string into a response object.
*
* @param string $message Response message string.
*
* @return Response
*/
public static function parseResponse($message)
{
$data = self::parseMessage($message);
// According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space
// between status-code and reason-phrase is required. But browsers accept
// responses without space and reason as well.
if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) {
throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']);
}
$parts = explode(' ', $data['start-line'], 3);
return new Response(
(int) $parts[1],
$data['headers'],
$data['body'],
explode('/', $parts[0])[1],
isset($parts[2]) ? $parts[2] : null
);
}
}

View File

@ -0,0 +1,269 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Trait implementing functionality common to requests and responses.
*/
trait MessageTrait
{
/** @var array Map of all registered headers, as original name => array of values */
private $headers = [];
/** @var array Map of lowercase header name => original name at registration */
private $headerNames = [];
/** @var string */
private $protocol = '1.1';
/** @var StreamInterface|null */
private $stream;
public function getProtocolVersion()
{
return $this->protocol;
}
public function withProtocolVersion($version)
{
if ($this->protocol === $version) {
return $this;
}
$new = clone $this;
$new->protocol = $version;
return $new;
}
public function getHeaders()
{
return $this->headers;
}
public function hasHeader($header)
{
return isset($this->headerNames[strtolower($header)]);
}
public function getHeader($header)
{
$header = strtolower($header);
if (!isset($this->headerNames[$header])) {
return [];
}
$header = $this->headerNames[$header];
return $this->headers[$header];
}
public function getHeaderLine($header)
{
return implode(', ', $this->getHeader($header));
}
public function withHeader($header, $value)
{
$this->assertHeader($header);
$value = $this->normalizeHeaderValue($value);
$normalized = strtolower($header);
$new = clone $this;
if (isset($new->headerNames[$normalized])) {
unset($new->headers[$new->headerNames[$normalized]]);
}
$new->headerNames[$normalized] = $header;
$new->headers[$header] = $value;
return $new;
}
public function withAddedHeader($header, $value)
{
$this->assertHeader($header);
$value = $this->normalizeHeaderValue($value);
$normalized = strtolower($header);
$new = clone $this;
if (isset($new->headerNames[$normalized])) {
$header = $this->headerNames[$normalized];
$new->headers[$header] = array_merge($this->headers[$header], $value);
} else {
$new->headerNames[$normalized] = $header;
$new->headers[$header] = $value;
}
return $new;
}
public function withoutHeader($header)
{
$normalized = strtolower($header);
if (!isset($this->headerNames[$normalized])) {
return $this;
}
$header = $this->headerNames[$normalized];
$new = clone $this;
unset($new->headers[$header], $new->headerNames[$normalized]);
return $new;
}
public function getBody()
{
if (!$this->stream) {
$this->stream = Utils::streamFor('');
}
return $this->stream;
}
public function withBody(StreamInterface $body)
{
if ($body === $this->stream) {
return $this;
}
$new = clone $this;
$new->stream = $body;
return $new;
}
private function setHeaders(array $headers)
{
$this->headerNames = $this->headers = [];
foreach ($headers as $header => $value) {
if (is_int($header)) {
// Numeric array keys are converted to int by PHP but having a header name '123' is not forbidden by the spec
// and also allowed in withHeader(). So we need to cast it to string again for the following assertion to pass.
$header = (string) $header;
}
$this->assertHeader($header);
$value = $this->normalizeHeaderValue($value);
$normalized = strtolower($header);
if (isset($this->headerNames[$normalized])) {
$header = $this->headerNames[$normalized];
$this->headers[$header] = array_merge($this->headers[$header], $value);
} else {
$this->headerNames[$normalized] = $header;
$this->headers[$header] = $value;
}
}
}
/**
* @param mixed $value
*
* @return string[]
*/
private function normalizeHeaderValue($value)
{
if (!is_array($value)) {
return $this->trimAndValidateHeaderValues([$value]);
}
if (count($value) === 0) {
throw new \InvalidArgumentException('Header value can not be an empty array.');
}
return $this->trimAndValidateHeaderValues($value);
}
/**
* Trims whitespace from the header values.
*
* Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field.
*
* header-field = field-name ":" OWS field-value OWS
* OWS = *( SP / HTAB )
*
* @param mixed[] $values Header values
*
* @return string[] Trimmed header values
*
* @see https://tools.ietf.org/html/rfc7230#section-3.2.4
*/
private function trimAndValidateHeaderValues(array $values)
{
return array_map(function ($value) {
if (!is_scalar($value) && null !== $value) {
throw new \InvalidArgumentException(sprintf(
'Header value must be scalar or null but %s provided.',
is_object($value) ? get_class($value) : gettype($value)
));
}
$trimmed = trim((string) $value, " \t");
$this->assertValue($trimmed);
return $trimmed;
}, array_values($values));
}
/**
* @see https://tools.ietf.org/html/rfc7230#section-3.2
*
* @param mixed $header
*
* @return void
*/
private function assertHeader($header)
{
if (!is_string($header)) {
throw new \InvalidArgumentException(sprintf(
'Header name must be a string but %s provided.',
is_object($header) ? get_class($header) : gettype($header)
));
}
if ($header === '') {
throw new \InvalidArgumentException('Header name can not be empty.');
}
if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $header)) {
throw new \InvalidArgumentException(
sprintf('"%s" is not valid header name.', $header)
);
}
}
/**
* @param string $value
*
* @return void
*
* @see https://tools.ietf.org/html/rfc7230#section-3.2
*
* field-value = *( field-content / obs-fold )
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* VCHAR = %x21-7E
* obs-text = %x80-FF
* obs-fold = CRLF 1*( SP / HTAB )
*/
private function assertValue($value)
{
// The regular expression intentionally does not support the obs-fold production, because as
// per RFC 7230#3.2.4:
//
// A sender MUST NOT generate a message that includes
// line folding (i.e., that has any field-value that contains a match to
// the obs-fold rule) unless the message is intended for packaging
// within the message/http media type.
//
// Clients must not send a request with line folding and a server sending folded headers is
// likely very rare. Line folding is a fairly obscure feature of HTTP/1.1 and thus not accepting
// folding is not likely to break any legitimate use case.
if (! preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value)) {
throw new \InvalidArgumentException(
sprintf('"%s" is not valid header value.', $value)
);
}
}
}

View File

@ -0,0 +1,140 @@
<?php
namespace GuzzleHttp\Psr7;
final class MimeType
{
/**
* Determines the mimetype of a file by looking at its extension.
*
* @param string $filename
*
* @return string|null
*/
public static function fromFilename($filename)
{
return self::fromExtension(pathinfo($filename, PATHINFO_EXTENSION));
}
/**
* Maps a file extensions to a mimetype.
*
* @param string $extension string The file extension.
*
* @return string|null
*
* @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
*/
public static function fromExtension($extension)
{
static $mimetypes = [
'3gp' => 'video/3gpp',
'7z' => 'application/x-7z-compressed',
'aac' => 'audio/x-aac',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'asc' => 'text/plain',
'asf' => 'video/x-ms-asf',
'atom' => 'application/atom+xml',
'avi' => 'video/x-msvideo',
'bmp' => 'image/bmp',
'bz2' => 'application/x-bzip2',
'cer' => 'application/pkix-cert',
'crl' => 'application/pkix-crl',
'crt' => 'application/x-x509-ca-cert',
'css' => 'text/css',
'csv' => 'text/csv',
'cu' => 'application/cu-seeme',
'deb' => 'application/x-debian-package',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dvi' => 'application/x-dvi',
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'epub' => 'application/epub+zip',
'etx' => 'text/x-setext',
'flac' => 'audio/flac',
'flv' => 'video/x-flv',
'gif' => 'image/gif',
'gz' => 'application/gzip',
'htm' => 'text/html',
'html' => 'text/html',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ini' => 'text/plain',
'iso' => 'application/x-iso9660-image',
'jar' => 'application/java-archive',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'text/javascript',
'json' => 'application/json',
'latex' => 'application/x-latex',
'log' => 'text/plain',
'm4a' => 'audio/mp4',
'm4v' => 'video/mp4',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mov' => 'video/quicktime',
'mkv' => 'video/x-matroska',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mp4a' => 'audio/mp4',
'mp4v' => 'video/mp4',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpg4' => 'video/mp4',
'oga' => 'audio/ogg',
'ogg' => 'audio/ogg',
'ogv' => 'video/ogg',
'ogx' => 'application/ogg',
'pbm' => 'image/x-portable-bitmap',
'pdf' => 'application/pdf',
'pgm' => 'image/x-portable-graymap',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'ppm' => 'image/x-portable-pixmap',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'ps' => 'application/postscript',
'qt' => 'video/quicktime',
'rar' => 'application/x-rar-compressed',
'ras' => 'image/x-cmu-raster',
'rss' => 'application/rss+xml',
'rtf' => 'application/rtf',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'svg' => 'image/svg+xml',
'swf' => 'application/x-shockwave-flash',
'tar' => 'application/x-tar',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'torrent' => 'application/x-bittorrent',
'ttf' => 'application/x-font-ttf',
'txt' => 'text/plain',
'wav' => 'audio/x-wav',
'webm' => 'video/webm',
'webp' => 'image/webp',
'wma' => 'audio/x-ms-wma',
'wmv' => 'video/x-ms-wmv',
'woff' => 'application/x-font-woff',
'wsdl' => 'application/wsdl+xml',
'xbm' => 'image/x-xbitmap',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xml' => 'application/xml',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'yaml' => 'text/yaml',
'yml' => 'text/yaml',
'zip' => 'application/zip',
];
$extension = strtolower($extension);
return isset($mimetypes[$extension])
? $mimetypes[$extension]
: null;
}
}

View File

@ -0,0 +1,158 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Stream that when read returns bytes for a streaming multipart or
* multipart/form-data stream.
*
* @final
*/
class MultipartStream implements StreamInterface
{
use StreamDecoratorTrait;
private $boundary;
/**
* @param array $elements Array of associative arrays, each containing a
* required "name" key mapping to the form field,
* name, a required "contents" key mapping to a
* StreamInterface/resource/string, an optional
* "headers" associative array of custom headers,
* and an optional "filename" key mapping to a
* string to send as the filename in the part.
* @param string $boundary You can optionally provide a specific boundary
*
* @throws \InvalidArgumentException
*/
public function __construct(array $elements = [], $boundary = null)
{
$this->boundary = $boundary ?: sha1(uniqid('', true));
$this->stream = $this->createStream($elements);
}
/**
* Get the boundary
*
* @return string
*/
public function getBoundary()
{
return $this->boundary;
}
public function isWritable()
{
return false;
}
/**
* Get the headers needed before transferring the content of a POST file
*/
private function getHeaders(array $headers)
{
$str = '';
foreach ($headers as $key => $value) {
$str .= "{$key}: {$value}\r\n";
}
return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n";
}
/**
* Create the aggregate stream that will be used to upload the POST data
*/
protected function createStream(array $elements)
{
$stream = new AppendStream();
foreach ($elements as $element) {
$this->addElement($stream, $element);
}
// Add the trailing boundary with CRLF
$stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n"));
return $stream;
}
private function addElement(AppendStream $stream, array $element)
{
foreach (['contents', 'name'] as $key) {
if (!array_key_exists($key, $element)) {
throw new \InvalidArgumentException("A '{$key}' key is required");
}
}
$element['contents'] = Utils::streamFor($element['contents']);
if (empty($element['filename'])) {
$uri = $element['contents']->getMetadata('uri');
if (substr($uri, 0, 6) !== 'php://') {
$element['filename'] = $uri;
}
}
list($body, $headers) = $this->createElement(
$element['name'],
$element['contents'],
isset($element['filename']) ? $element['filename'] : null,
isset($element['headers']) ? $element['headers'] : []
);
$stream->addStream(Utils::streamFor($this->getHeaders($headers)));
$stream->addStream($body);
$stream->addStream(Utils::streamFor("\r\n"));
}
/**
* @return array
*/
private function createElement($name, StreamInterface $stream, $filename, array $headers)
{
// Set a default content-disposition header if one was no provided
$disposition = $this->getHeader($headers, 'content-disposition');
if (!$disposition) {
$headers['Content-Disposition'] = ($filename === '0' || $filename)
? sprintf(
'form-data; name="%s"; filename="%s"',
$name,
basename($filename)
)
: "form-data; name=\"{$name}\"";
}
// Set a default content-length header if one was no provided
$length = $this->getHeader($headers, 'content-length');
if (!$length) {
if ($length = $stream->getSize()) {
$headers['Content-Length'] = (string) $length;
}
}
// Set a default Content-Type if one was not supplied
$type = $this->getHeader($headers, 'content-type');
if (!$type && ($filename === '0' || $filename)) {
if ($type = MimeType::fromFilename($filename)) {
$headers['Content-Type'] = $type;
}
}
return [$stream, $headers];
}
private function getHeader(array $headers, $key)
{
$lowercaseHeader = strtolower($key);
foreach ($headers as $k => $v) {
if (strtolower($k) === $lowercaseHeader) {
return $v;
}
}
return null;
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Stream decorator that prevents a stream from being seeked.
*
* @final
*/
class NoSeekStream implements StreamInterface
{
use StreamDecoratorTrait;
public function seek($offset, $whence = SEEK_SET)
{
throw new \RuntimeException('Cannot seek a NoSeekStream');
}
public function isSeekable()
{
return false;
}
}

View File

@ -0,0 +1,170 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Provides a read only stream that pumps data from a PHP callable.
*
* When invoking the provided callable, the PumpStream will pass the amount of
* data requested to read to the callable. The callable can choose to ignore
* this value and return fewer or more bytes than requested. Any extra data
* returned by the provided callable is buffered internally until drained using
* the read() function of the PumpStream. The provided callable MUST return
* false when there is no more data to read.
*
* @final
*/
class PumpStream implements StreamInterface
{
/** @var callable */
private $source;
/** @var int */
private $size;
/** @var int */
private $tellPos = 0;
/** @var array */
private $metadata;
/** @var BufferStream */
private $buffer;
/**
* @param callable $source Source of the stream data. The callable MAY
* accept an integer argument used to control the
* amount of data to return. The callable MUST
* return a string when called, or false on error
* or EOF.
* @param array $options Stream options:
* - metadata: Hash of metadata to use with stream.
* - size: Size of the stream, if known.
*/
public function __construct(callable $source, array $options = [])
{
$this->source = $source;
$this->size = isset($options['size']) ? $options['size'] : null;
$this->metadata = isset($options['metadata']) ? $options['metadata'] : [];
$this->buffer = new BufferStream();
}
public function __toString()
{
try {
return Utils::copyToString($this);
} catch (\Exception $e) {
return '';
}
}
public function close()
{
$this->detach();
}
public function detach()
{
$this->tellPos = false;
$this->source = null;
return null;
}
public function getSize()
{
return $this->size;
}
public function tell()
{
return $this->tellPos;
}
public function eof()
{
return !$this->source;
}
public function isSeekable()
{
return false;
}
public function rewind()
{
$this->seek(0);
}
public function seek($offset, $whence = SEEK_SET)
{
throw new \RuntimeException('Cannot seek a PumpStream');
}
public function isWritable()
{
return false;
}
public function write($string)
{
throw new \RuntimeException('Cannot write to a PumpStream');
}
public function isReadable()
{
return true;
}
public function read($length)
{
$data = $this->buffer->read($length);
$readLen = strlen($data);
$this->tellPos += $readLen;
$remaining = $length - $readLen;
if ($remaining) {
$this->pump($remaining);
$data .= $this->buffer->read($remaining);
$this->tellPos += strlen($data) - $readLen;
}
return $data;
}
public function getContents()
{
$result = '';
while (!$this->eof()) {
$result .= $this->read(1000000);
}
return $result;
}
public function getMetadata($key = null)
{
if (!$key) {
return $this->metadata;
}
return isset($this->metadata[$key]) ? $this->metadata[$key] : null;
}
private function pump($length)
{
if ($this->source) {
do {
$data = call_user_func($this->source, $length);
if ($data === false || $data === null) {
$this->source = null;
return;
}
$this->buffer->write($data);
$length -= strlen($data);
} while ($length > 0);
}
}
}

View File

@ -0,0 +1,113 @@
<?php
namespace GuzzleHttp\Psr7;
final class Query
{
/**
* Parse a query string into an associative array.
*
* If multiple values are found for the same key, the value of that key
* value pair will become an array. This function does not parse nested
* PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2`
* will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`.
*
* @param string $str Query string to parse
* @param int|bool $urlEncoding How the query string is encoded
*
* @return array
*/
public static function parse($str, $urlEncoding = true)
{
$result = [];
if ($str === '') {
return $result;
}
if ($urlEncoding === true) {
$decoder = function ($value) {
return rawurldecode(str_replace('+', ' ', $value));
};
} elseif ($urlEncoding === PHP_QUERY_RFC3986) {
$decoder = 'rawurldecode';
} elseif ($urlEncoding === PHP_QUERY_RFC1738) {
$decoder = 'urldecode';
} else {
$decoder = function ($str) {
return $str;
};
}
foreach (explode('&', $str) as $kvp) {
$parts = explode('=', $kvp, 2);
$key = $decoder($parts[0]);
$value = isset($parts[1]) ? $decoder($parts[1]) : null;
if (!isset($result[$key])) {
$result[$key] = $value;
} else {
if (!is_array($result[$key])) {
$result[$key] = [$result[$key]];
}
$result[$key][] = $value;
}
}
return $result;
}
/**
* Build a query string from an array of key value pairs.
*
* This function can use the return value of `parse()` to build a query
* string. This function does not modify the provided keys when an array is
* encountered (like `http_build_query()` would).
*
* @param array $params Query string parameters.
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
* to encode using RFC3986, or PHP_QUERY_RFC1738
* to encode using RFC1738.
*
* @return string
*/
public static function build(array $params, $encoding = PHP_QUERY_RFC3986)
{
if (!$params) {
return '';
}
if ($encoding === false) {
$encoder = function ($str) {
return $str;
};
} elseif ($encoding === PHP_QUERY_RFC3986) {
$encoder = 'rawurlencode';
} elseif ($encoding === PHP_QUERY_RFC1738) {
$encoder = 'urlencode';
} else {
throw new \InvalidArgumentException('Invalid type');
}
$qs = '';
foreach ($params as $k => $v) {
$k = $encoder($k);
if (!is_array($v)) {
$qs .= $k;
if ($v !== null) {
$qs .= '=' . $encoder($v);
}
$qs .= '&';
} else {
foreach ($v as $vv) {
$qs .= $k;
if ($vv !== null) {
$qs .= '=' . $encoder($vv);
}
$qs .= '&';
}
}
}
return $qs ? (string) substr($qs, 0, -1) : '';
}
}

View File

@ -0,0 +1,152 @@
<?php
namespace GuzzleHttp\Psr7;
use InvalidArgumentException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
/**
* PSR-7 request implementation.
*/
class Request implements RequestInterface
{
use MessageTrait;
/** @var string */
private $method;
/** @var string|null */
private $requestTarget;
/** @var UriInterface */
private $uri;
/**
* @param string $method HTTP method
* @param string|UriInterface $uri URI
* @param array $headers Request headers
* @param string|resource|StreamInterface|null $body Request body
* @param string $version Protocol version
*/
public function __construct(
$method,
$uri,
array $headers = [],
$body = null,
$version = '1.1'
) {
$this->assertMethod($method);
if (!($uri instanceof UriInterface)) {
$uri = new Uri($uri);
}
$this->method = strtoupper($method);
$this->uri = $uri;
$this->setHeaders($headers);
$this->protocol = $version;
if (!isset($this->headerNames['host'])) {
$this->updateHostFromUri();
}
if ($body !== '' && $body !== null) {
$this->stream = Utils::streamFor($body);
}
}
public function getRequestTarget()
{
if ($this->requestTarget !== null) {
return $this->requestTarget;
}
$target = $this->uri->getPath();
if ($target == '') {
$target = '/';
}
if ($this->uri->getQuery() != '') {
$target .= '?' . $this->uri->getQuery();
}
return $target;
}
public function withRequestTarget($requestTarget)
{
if (preg_match('#\s#', $requestTarget)) {
throw new InvalidArgumentException(
'Invalid request target provided; cannot contain whitespace'
);
}
$new = clone $this;
$new->requestTarget = $requestTarget;
return $new;
}
public function getMethod()
{
return $this->method;
}
public function withMethod($method)
{
$this->assertMethod($method);
$new = clone $this;
$new->method = strtoupper($method);
return $new;
}
public function getUri()
{
return $this->uri;
}
public function withUri(UriInterface $uri, $preserveHost = false)
{
if ($uri === $this->uri) {
return $this;
}
$new = clone $this;
$new->uri = $uri;
if (!$preserveHost || !isset($this->headerNames['host'])) {
$new->updateHostFromUri();
}
return $new;
}
private function updateHostFromUri()
{
$host = $this->uri->getHost();
if ($host == '') {
return;
}
if (($port = $this->uri->getPort()) !== null) {
$host .= ':' . $port;
}
if (isset($this->headerNames['host'])) {
$header = $this->headerNames['host'];
} else {
$header = 'Host';
$this->headerNames['host'] = 'Host';
}
// Ensure Host is the first header.
// See: http://tools.ietf.org/html/rfc7230#section-5.4
$this->headers = [$header => [$host]] + $this->headers;
}
private function assertMethod($method)
{
if (!is_string($method) || $method === '') {
throw new \InvalidArgumentException('Method must be a non-empty string.');
}
}
}

View File

@ -0,0 +1,155 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* PSR-7 response implementation.
*/
class Response implements ResponseInterface
{
use MessageTrait;
/** @var array Map of standard HTTP status code/reason phrases */
private static $phrases = [
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-status',
208 => 'Already Reported',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Switch Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
451 => 'Unavailable For Legal Reasons',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
511 => 'Network Authentication Required',
];
/** @var string */
private $reasonPhrase = '';
/** @var int */
private $statusCode = 200;
/**
* @param int $status Status code
* @param array $headers Response headers
* @param string|resource|StreamInterface|null $body Response body
* @param string $version Protocol version
* @param string|null $reason Reason phrase (when empty a default will be used based on the status code)
*/
public function __construct(
$status = 200,
array $headers = [],
$body = null,
$version = '1.1',
$reason = null
) {
$this->assertStatusCodeIsInteger($status);
$status = (int) $status;
$this->assertStatusCodeRange($status);
$this->statusCode = $status;
if ($body !== '' && $body !== null) {
$this->stream = Utils::streamFor($body);
}
$this->setHeaders($headers);
if ($reason == '' && isset(self::$phrases[$this->statusCode])) {
$this->reasonPhrase = self::$phrases[$this->statusCode];
} else {
$this->reasonPhrase = (string) $reason;
}
$this->protocol = $version;
}
public function getStatusCode()
{
return $this->statusCode;
}
public function getReasonPhrase()
{
return $this->reasonPhrase;
}
public function withStatus($code, $reasonPhrase = '')
{
$this->assertStatusCodeIsInteger($code);
$code = (int) $code;
$this->assertStatusCodeRange($code);
$new = clone $this;
$new->statusCode = $code;
if ($reasonPhrase == '' && isset(self::$phrases[$new->statusCode])) {
$reasonPhrase = self::$phrases[$new->statusCode];
}
$new->reasonPhrase = (string) $reasonPhrase;
return $new;
}
private function assertStatusCodeIsInteger($statusCode)
{
if (filter_var($statusCode, FILTER_VALIDATE_INT) === false) {
throw new \InvalidArgumentException('Status code must be an integer value.');
}
}
private function assertStatusCodeRange($statusCode)
{
if ($statusCode < 100 || $statusCode >= 600) {
throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.');
}
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace GuzzleHttp\Psr7;
final class Rfc7230
{
/**
* Header related regular expressions (copied from amphp/http package)
* (Note: once we require PHP 7.x we could just depend on the upstream package)
*
* Note: header delimiter (\r\n) is modified to \r?\n to accept line feed only delimiters for BC reasons.
*
* @link https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
*
* @license https://github.com/amphp/http/blob/v1.0.1/LICENSE
*/
const HEADER_REGEX = "(^([^()<>@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m";
const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)";
}

View File

@ -0,0 +1,379 @@
<?php
namespace GuzzleHttp\Psr7;
use InvalidArgumentException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Http\Message\UriInterface;
/**
* Server-side HTTP request
*
* Extends the Request definition to add methods for accessing incoming data,
* specifically server parameters, cookies, matched path parameters, query
* string arguments, body parameters, and upload file information.
*
* "Attributes" are discovered via decomposing the request (and usually
* specifically the URI path), and typically will be injected by the application.
*
* Requests are considered immutable; all methods that might change state are
* implemented such that they retain the internal state of the current
* message and return a new instance that contains the changed state.
*/
class ServerRequest extends Request implements ServerRequestInterface
{
/**
* @var array
*/
private $attributes = [];
/**
* @var array
*/
private $cookieParams = [];
/**
* @var array|object|null
*/
private $parsedBody;
/**
* @var array
*/
private $queryParams = [];
/**
* @var array
*/
private $serverParams;
/**
* @var array
*/
private $uploadedFiles = [];
/**
* @param string $method HTTP method
* @param string|UriInterface $uri URI
* @param array $headers Request headers
* @param string|resource|StreamInterface|null $body Request body
* @param string $version Protocol version
* @param array $serverParams Typically the $_SERVER superglobal
*/
public function __construct(
$method,
$uri,
array $headers = [],
$body = null,
$version = '1.1',
array $serverParams = []
) {
$this->serverParams = $serverParams;
parent::__construct($method, $uri, $headers, $body, $version);
}
/**
* Return an UploadedFile instance array.
*
* @param array $files A array which respect $_FILES structure
*
* @return array
*
* @throws InvalidArgumentException for unrecognized values
*/
public static function normalizeFiles(array $files)
{
$normalized = [];
foreach ($files as $key => $value) {
if ($value instanceof UploadedFileInterface) {
$normalized[$key] = $value;
} elseif (is_array($value) && isset($value['tmp_name'])) {
$normalized[$key] = self::createUploadedFileFromSpec($value);
} elseif (is_array($value)) {
$normalized[$key] = self::normalizeFiles($value);
continue;
} else {
throw new InvalidArgumentException('Invalid value in files specification');
}
}
return $normalized;
}
/**
* Create and return an UploadedFile instance from a $_FILES specification.
*
* If the specification represents an array of values, this method will
* delegate to normalizeNestedFileSpec() and return that return value.
*
* @param array $value $_FILES struct
*
* @return array|UploadedFileInterface
*/
private static function createUploadedFileFromSpec(array $value)
{
if (is_array($value['tmp_name'])) {
return self::normalizeNestedFileSpec($value);
}
return new UploadedFile(
$value['tmp_name'],
(int) $value['size'],
(int) $value['error'],
$value['name'],
$value['type']
);
}
/**
* Normalize an array of file specifications.
*
* Loops through all nested files and returns a normalized array of
* UploadedFileInterface instances.
*
* @param array $files
*
* @return UploadedFileInterface[]
*/
private static function normalizeNestedFileSpec(array $files = [])
{
$normalizedFiles = [];
foreach (array_keys($files['tmp_name']) as $key) {
$spec = [
'tmp_name' => $files['tmp_name'][$key],
'size' => $files['size'][$key],
'error' => $files['error'][$key],
'name' => $files['name'][$key],
'type' => $files['type'][$key],
];
$normalizedFiles[$key] = self::createUploadedFileFromSpec($spec);
}
return $normalizedFiles;
}
/**
* Return a ServerRequest populated with superglobals:
* $_GET
* $_POST
* $_COOKIE
* $_FILES
* $_SERVER
*
* @return ServerRequestInterface
*/
public static function fromGlobals()
{
$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
$headers = getallheaders();
$uri = self::getUriFromGlobals();
$body = new CachingStream(new LazyOpenStream('php://input', 'r+'));
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1';
$serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER);
return $serverRequest
->withCookieParams($_COOKIE)
->withQueryParams($_GET)
->withParsedBody($_POST)
->withUploadedFiles(self::normalizeFiles($_FILES));
}
private static function extractHostAndPortFromAuthority($authority)
{
$uri = 'http://' . $authority;
$parts = parse_url($uri);
if (false === $parts) {
return [null, null];
}
$host = isset($parts['host']) ? $parts['host'] : null;
$port = isset($parts['port']) ? $parts['port'] : null;
return [$host, $port];
}
/**
* Get a Uri populated with values from $_SERVER.
*
* @return UriInterface
*/
public static function getUriFromGlobals()
{
$uri = new Uri('');
$uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http');
$hasPort = false;
if (isset($_SERVER['HTTP_HOST'])) {
list($host, $port) = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']);
if ($host !== null) {
$uri = $uri->withHost($host);
}
if ($port !== null) {
$hasPort = true;
$uri = $uri->withPort($port);
}
} elseif (isset($_SERVER['SERVER_NAME'])) {
$uri = $uri->withHost($_SERVER['SERVER_NAME']);
} elseif (isset($_SERVER['SERVER_ADDR'])) {
$uri = $uri->withHost($_SERVER['SERVER_ADDR']);
}
if (!$hasPort && isset($_SERVER['SERVER_PORT'])) {
$uri = $uri->withPort($_SERVER['SERVER_PORT']);
}
$hasQuery = false;
if (isset($_SERVER['REQUEST_URI'])) {
$requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2);
$uri = $uri->withPath($requestUriParts[0]);
if (isset($requestUriParts[1])) {
$hasQuery = true;
$uri = $uri->withQuery($requestUriParts[1]);
}
}
if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) {
$uri = $uri->withQuery($_SERVER['QUERY_STRING']);
}
return $uri;
}
/**
* {@inheritdoc}
*/
public function getServerParams()
{
return $this->serverParams;
}
/**
* {@inheritdoc}
*/
public function getUploadedFiles()
{
return $this->uploadedFiles;
}
/**
* {@inheritdoc}
*/
public function withUploadedFiles(array $uploadedFiles)
{
$new = clone $this;
$new->uploadedFiles = $uploadedFiles;
return $new;
}
/**
* {@inheritdoc}
*/
public function getCookieParams()
{
return $this->cookieParams;
}
/**
* {@inheritdoc}
*/
public function withCookieParams(array $cookies)
{
$new = clone $this;
$new->cookieParams = $cookies;
return $new;
}
/**
* {@inheritdoc}
*/
public function getQueryParams()
{
return $this->queryParams;
}
/**
* {@inheritdoc}
*/
public function withQueryParams(array $query)
{
$new = clone $this;
$new->queryParams = $query;
return $new;
}
/**
* {@inheritdoc}
*/
public function getParsedBody()
{
return $this->parsedBody;
}
/**
* {@inheritdoc}
*/
public function withParsedBody($data)
{
$new = clone $this;
$new->parsedBody = $data;
return $new;
}
/**
* {@inheritdoc}
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* {@inheritdoc}
*/
public function getAttribute($attribute, $default = null)
{
if (false === array_key_exists($attribute, $this->attributes)) {
return $default;
}
return $this->attributes[$attribute];
}
/**
* {@inheritdoc}
*/
public function withAttribute($attribute, $value)
{
$new = clone $this;
$new->attributes[$attribute] = $value;
return $new;
}
/**
* {@inheritdoc}
*/
public function withoutAttribute($attribute)
{
if (false === array_key_exists($attribute, $this->attributes)) {
return $this;
}
$new = clone $this;
unset($new->attributes[$attribute]);
return $new;
}
}

View File

@ -0,0 +1,270 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* PHP stream implementation.
*
* @var $stream
*/
class Stream implements StreamInterface
{
/**
* Resource modes.
*
* @var string
*
* @see http://php.net/manual/function.fopen.php
* @see http://php.net/manual/en/function.gzopen.php
*/
const READABLE_MODES = '/r|a\+|ab\+|w\+|wb\+|x\+|xb\+|c\+|cb\+/';
const WRITABLE_MODES = '/a|w|r\+|rb\+|rw|x|c/';
private $stream;
private $size;
private $seekable;
private $readable;
private $writable;
private $uri;
private $customMetadata;
/**
* This constructor accepts an associative array of options.
*
* - size: (int) If a read stream would otherwise have an indeterminate
* size, but the size is known due to foreknowledge, then you can
* provide that size, in bytes.
* - metadata: (array) Any additional metadata to return when the metadata
* of the stream is accessed.
*
* @param resource $stream Stream resource to wrap.
* @param array $options Associative array of options.
*
* @throws \InvalidArgumentException if the stream is not a stream resource
*/
public function __construct($stream, $options = [])
{
if (!is_resource($stream)) {
throw new \InvalidArgumentException('Stream must be a resource');
}
if (isset($options['size'])) {
$this->size = $options['size'];
}
$this->customMetadata = isset($options['metadata'])
? $options['metadata']
: [];
$this->stream = $stream;
$meta = stream_get_meta_data($this->stream);
$this->seekable = $meta['seekable'];
$this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']);
$this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']);
$this->uri = $this->getMetadata('uri');
}
/**
* Closes the stream when the destructed
*/
public function __destruct()
{
$this->close();
}
public function __toString()
{
try {
if ($this->isSeekable()) {
$this->seek(0);
}
return $this->getContents();
} catch (\Exception $e) {
return '';
}
}
public function getContents()
{
if (!isset($this->stream)) {
throw new \RuntimeException('Stream is detached');
}
$contents = stream_get_contents($this->stream);
if ($contents === false) {
throw new \RuntimeException('Unable to read stream contents');
}
return $contents;
}
public function close()
{
if (isset($this->stream)) {
if (is_resource($this->stream)) {
fclose($this->stream);
}
$this->detach();
}
}
public function detach()
{
if (!isset($this->stream)) {
return null;
}
$result = $this->stream;
unset($this->stream);
$this->size = $this->uri = null;
$this->readable = $this->writable = $this->seekable = false;
return $result;
}
public function getSize()
{
if ($this->size !== null) {
return $this->size;
}
if (!isset($this->stream)) {
return null;
}
// Clear the stat cache if the stream has a URI
if ($this->uri) {
clearstatcache(true, $this->uri);
}
$stats = fstat($this->stream);
if (isset($stats['size'])) {
$this->size = $stats['size'];
return $this->size;
}
return null;
}
public function isReadable()
{
return $this->readable;
}
public function isWritable()
{
return $this->writable;
}
public function isSeekable()
{
return $this->seekable;
}
public function eof()
{
if (!isset($this->stream)) {
throw new \RuntimeException('Stream is detached');
}
return feof($this->stream);
}
public function tell()
{
if (!isset($this->stream)) {
throw new \RuntimeException('Stream is detached');
}
$result = ftell($this->stream);
if ($result === false) {
throw new \RuntimeException('Unable to determine stream position');
}
return $result;
}
public function rewind()
{
$this->seek(0);
}
public function seek($offset, $whence = SEEK_SET)
{
$whence = (int) $whence;
if (!isset($this->stream)) {
throw new \RuntimeException('Stream is detached');
}
if (!$this->seekable) {
throw new \RuntimeException('Stream is not seekable');
}
if (fseek($this->stream, $offset, $whence) === -1) {
throw new \RuntimeException('Unable to seek to stream position '
. $offset . ' with whence ' . var_export($whence, true));
}
}
public function read($length)
{
if (!isset($this->stream)) {
throw new \RuntimeException('Stream is detached');
}
if (!$this->readable) {
throw new \RuntimeException('Cannot read from non-readable stream');
}
if ($length < 0) {
throw new \RuntimeException('Length parameter cannot be negative');
}
if (0 === $length) {
return '';
}
$string = fread($this->stream, $length);
if (false === $string) {
throw new \RuntimeException('Unable to read from stream');
}
return $string;
}
public function write($string)
{
if (!isset($this->stream)) {
throw new \RuntimeException('Stream is detached');
}
if (!$this->writable) {
throw new \RuntimeException('Cannot write to a non-writable stream');
}
// We can't know the size after writing anything
$this->size = null;
$result = fwrite($this->stream, $string);
if ($result === false) {
throw new \RuntimeException('Unable to write to stream');
}
return $result;
}
public function getMetadata($key = null)
{
if (!isset($this->stream)) {
return $key ? null : [];
} elseif (!$key) {
return $this->customMetadata + stream_get_meta_data($this->stream);
} elseif (isset($this->customMetadata[$key])) {
return $this->customMetadata[$key];
}
$meta = stream_get_meta_data($this->stream);
return isset($meta[$key]) ? $meta[$key] : null;
}
}

View File

@ -0,0 +1,152 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Stream decorator trait
*
* @property StreamInterface stream
*/
trait StreamDecoratorTrait
{
/**
* @param StreamInterface $stream Stream to decorate
*/
public function __construct(StreamInterface $stream)
{
$this->stream = $stream;
}
/**
* Magic method used to create a new stream if streams are not added in
* the constructor of a decorator (e.g., LazyOpenStream).
*
* @param string $name Name of the property (allows "stream" only).
*
* @return StreamInterface
*/
public function __get($name)
{
if ($name == 'stream') {
$this->stream = $this->createStream();
return $this->stream;
}
throw new \UnexpectedValueException("$name not found on class");
}
public function __toString()
{
try {
if ($this->isSeekable()) {
$this->seek(0);
}
return $this->getContents();
} catch (\Exception $e) {
// Really, PHP? https://bugs.php.net/bug.php?id=53648
trigger_error('StreamDecorator::__toString exception: '
. (string) $e, E_USER_ERROR);
return '';
}
}
public function getContents()
{
return Utils::copyToString($this);
}
/**
* Allow decorators to implement custom methods
*
* @param string $method Missing method name
* @param array $args Method arguments
*
* @return mixed
*/
public function __call($method, array $args)
{
$result = call_user_func_array([$this->stream, $method], $args);
// Always return the wrapped object if the result is a return $this
return $result === $this->stream ? $this : $result;
}
public function close()
{
$this->stream->close();
}
public function getMetadata($key = null)
{
return $this->stream->getMetadata($key);
}
public function detach()
{
return $this->stream->detach();
}
public function getSize()
{
return $this->stream->getSize();
}
public function eof()
{
return $this->stream->eof();
}
public function tell()
{
return $this->stream->tell();
}
public function isReadable()
{
return $this->stream->isReadable();
}
public function isWritable()
{
return $this->stream->isWritable();
}
public function isSeekable()
{
return $this->stream->isSeekable();
}
public function rewind()
{
$this->seek(0);
}
public function seek($offset, $whence = SEEK_SET)
{
$this->stream->seek($offset, $whence);
}
public function read($length)
{
return $this->stream->read($length);
}
public function write($string)
{
return $this->stream->write($string);
}
/**
* Implement in subclasses to dynamically create streams when requested.
*
* @return StreamInterface
*
* @throws \BadMethodCallException
*/
protected function createStream()
{
throw new \BadMethodCallException('Not implemented');
}
}

View File

@ -0,0 +1,165 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
/**
* Converts Guzzle streams into PHP stream resources.
*
* @final
*/
class StreamWrapper
{
/** @var resource */
public $context;
/** @var StreamInterface */
private $stream;
/** @var string r, r+, or w */
private $mode;
/**
* Returns a resource representing the stream.
*
* @param StreamInterface $stream The stream to get a resource for
*
* @return resource
*
* @throws \InvalidArgumentException if stream is not readable or writable
*/
public static function getResource(StreamInterface $stream)
{
self::register();
if ($stream->isReadable()) {
$mode = $stream->isWritable() ? 'r+' : 'r';
} elseif ($stream->isWritable()) {
$mode = 'w';
} else {
throw new \InvalidArgumentException('The stream must be readable, '
. 'writable, or both.');
}
return fopen('guzzle://stream', $mode, null, self::createStreamContext($stream));
}
/**
* Creates a stream context that can be used to open a stream as a php stream resource.
*
* @param StreamInterface $stream
*
* @return resource
*/
public static function createStreamContext(StreamInterface $stream)
{
return stream_context_create([
'guzzle' => ['stream' => $stream]
]);
}
/**
* Registers the stream wrapper if needed
*/
public static function register()
{
if (!in_array('guzzle', stream_get_wrappers())) {
stream_wrapper_register('guzzle', __CLASS__);
}
}
public function stream_open($path, $mode, $options, &$opened_path)
{
$options = stream_context_get_options($this->context);
if (!isset($options['guzzle']['stream'])) {
return false;
}
$this->mode = $mode;
$this->stream = $options['guzzle']['stream'];
return true;
}
public function stream_read($count)
{
return $this->stream->read($count);
}
public function stream_write($data)
{
return (int) $this->stream->write($data);
}
public function stream_tell()
{
return $this->stream->tell();
}
public function stream_eof()
{
return $this->stream->eof();
}
public function stream_seek($offset, $whence)
{
$this->stream->seek($offset, $whence);
return true;
}
public function stream_cast($cast_as)
{
$stream = clone($this->stream);
return $stream->detach();
}
public function stream_stat()
{
static $modeMap = [
'r' => 33060,
'rb' => 33060,
'r+' => 33206,
'w' => 33188,
'wb' => 33188
];
return [
'dev' => 0,
'ino' => 0,
'mode' => $modeMap[$this->mode],
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => $this->stream->getSize() ?: 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => 0,
'blocks' => 0
];
}
public function url_stat($path, $flags)
{
return [
'dev' => 0,
'ino' => 0,
'mode' => 0,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => 0,
'blocks' => 0
];
}
}

View File

@ -0,0 +1,328 @@
<?php
namespace GuzzleHttp\Psr7;
use InvalidArgumentException;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
use RuntimeException;
class UploadedFile implements UploadedFileInterface
{
/**
* @var int[]
*/
private static $errors = [
UPLOAD_ERR_OK,
UPLOAD_ERR_INI_SIZE,
UPLOAD_ERR_FORM_SIZE,
UPLOAD_ERR_PARTIAL,
UPLOAD_ERR_NO_FILE,
UPLOAD_ERR_NO_TMP_DIR,
UPLOAD_ERR_CANT_WRITE,
UPLOAD_ERR_EXTENSION,
];
/**
* @var string
*/
private $clientFilename;
/**
* @var string
*/
private $clientMediaType;
/**
* @var int
*/
private $error;
/**
* @var string|null
*/
private $file;
/**
* @var bool
*/
private $moved = false;
/**
* @var int
*/
private $size;
/**
* @var StreamInterface|null
*/
private $stream;
/**
* @param StreamInterface|string|resource $streamOrFile
* @param int $size
* @param int $errorStatus
* @param string|null $clientFilename
* @param string|null $clientMediaType
*/
public function __construct(
$streamOrFile,
$size,
$errorStatus,
$clientFilename = null,
$clientMediaType = null
) {
$this->setError($errorStatus);
$this->setSize($size);
$this->setClientFilename($clientFilename);
$this->setClientMediaType($clientMediaType);
if ($this->isOk()) {
$this->setStreamOrFile($streamOrFile);
}
}
/**
* Depending on the value set file or stream variable
*
* @param mixed $streamOrFile
*
* @throws InvalidArgumentException
*/
private function setStreamOrFile($streamOrFile)
{
if (is_string($streamOrFile)) {
$this->file = $streamOrFile;
} elseif (is_resource($streamOrFile)) {
$this->stream = new Stream($streamOrFile);
} elseif ($streamOrFile instanceof StreamInterface) {
$this->stream = $streamOrFile;
} else {
throw new InvalidArgumentException(
'Invalid stream or file provided for UploadedFile'
);
}
}
/**
* @param int $error
*
* @throws InvalidArgumentException
*/
private function setError($error)
{
if (false === is_int($error)) {
throw new InvalidArgumentException(
'Upload file error status must be an integer'
);
}
if (false === in_array($error, UploadedFile::$errors)) {
throw new InvalidArgumentException(
'Invalid error status for UploadedFile'
);
}
$this->error = $error;
}
/**
* @param int $size
*
* @throws InvalidArgumentException
*/
private function setSize($size)
{
if (false === is_int($size)) {
throw new InvalidArgumentException(
'Upload file size must be an integer'
);
}
$this->size = $size;
}
/**
* @param mixed $param
*
* @return bool
*/
private function isStringOrNull($param)
{
return in_array(gettype($param), ['string', 'NULL']);
}
/**
* @param mixed $param
*
* @return bool
*/
private function isStringNotEmpty($param)
{
return is_string($param) && false === empty($param);
}
/**
* @param string|null $clientFilename
*
* @throws InvalidArgumentException
*/
private function setClientFilename($clientFilename)
{
if (false === $this->isStringOrNull($clientFilename)) {
throw new InvalidArgumentException(
'Upload file client filename must be a string or null'
);
}
$this->clientFilename = $clientFilename;
}
/**
* @param string|null $clientMediaType
*
* @throws InvalidArgumentException
*/
private function setClientMediaType($clientMediaType)
{
if (false === $this->isStringOrNull($clientMediaType)) {
throw new InvalidArgumentException(
'Upload file client media type must be a string or null'
);
}
$this->clientMediaType = $clientMediaType;
}
/**
* Return true if there is no upload error
*
* @return bool
*/
private function isOk()
{
return $this->error === UPLOAD_ERR_OK;
}
/**
* @return bool
*/
public function isMoved()
{
return $this->moved;
}
/**
* @throws RuntimeException if is moved or not ok
*/
private function validateActive()
{
if (false === $this->isOk()) {
throw new RuntimeException('Cannot retrieve stream due to upload error');
}
if ($this->isMoved()) {
throw new RuntimeException('Cannot retrieve stream after it has already been moved');
}
}
/**
* {@inheritdoc}
*
* @throws RuntimeException if the upload was not successful.
*/
public function getStream()
{
$this->validateActive();
if ($this->stream instanceof StreamInterface) {
return $this->stream;
}
return new LazyOpenStream($this->file, 'r+');
}
/**
* {@inheritdoc}
*
* @see http://php.net/is_uploaded_file
* @see http://php.net/move_uploaded_file
*
* @param string $targetPath Path to which to move the uploaded file.
*
* @throws RuntimeException if the upload was not successful.
* @throws InvalidArgumentException if the $path specified is invalid.
* @throws RuntimeException on any error during the move operation, or on
* the second or subsequent call to the method.
*/
public function moveTo($targetPath)
{
$this->validateActive();
if (false === $this->isStringNotEmpty($targetPath)) {
throw new InvalidArgumentException(
'Invalid path provided for move operation; must be a non-empty string'
);
}
if ($this->file) {
$this->moved = php_sapi_name() == 'cli'
? rename($this->file, $targetPath)
: move_uploaded_file($this->file, $targetPath);
} else {
Utils::copyToStream(
$this->getStream(),
new LazyOpenStream($targetPath, 'w')
);
$this->moved = true;
}
if (false === $this->moved) {
throw new RuntimeException(
sprintf('Uploaded file could not be moved to %s', $targetPath)
);
}
}
/**
* {@inheritdoc}
*
* @return int|null The file size in bytes or null if unknown.
*/
public function getSize()
{
return $this->size;
}
/**
* {@inheritdoc}
*
* @see http://php.net/manual/en/features.file-upload.errors.php
*
* @return int One of PHP's UPLOAD_ERR_XXX constants.
*/
public function getError()
{
return $this->error;
}
/**
* {@inheritdoc}
*
* @return string|null The filename sent by the client or null if none
* was provided.
*/
public function getClientFilename()
{
return $this->clientFilename;
}
/**
* {@inheritdoc}
*/
public function getClientMediaType()
{
return $this->clientMediaType;
}
}

View File

@ -0,0 +1,810 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\UriInterface;
/**
* PSR-7 URI implementation.
*
* @author Michael Dowling
* @author Tobias Schultze
* @author Matthew Weier O'Phinney
*/
class Uri implements UriInterface
{
/**
* Absolute http and https URIs require a host per RFC 7230 Section 2.7
* but in generic URIs the host can be empty. So for http(s) URIs
* we apply this default host when no host is given yet to form a
* valid URI.
*/
const HTTP_DEFAULT_HOST = 'localhost';
private static $defaultPorts = [
'http' => 80,
'https' => 443,
'ftp' => 21,
'gopher' => 70,
'nntp' => 119,
'news' => 119,
'telnet' => 23,
'tn3270' => 23,
'imap' => 143,
'pop' => 110,
'ldap' => 389,
];
private static $charUnreserved = 'a-zA-Z0-9_\-\.~';
private static $charSubDelims = '!\$&\'\(\)\*\+,;=';
private static $replaceQuery = ['=' => '%3D', '&' => '%26'];
/** @var string Uri scheme. */
private $scheme = '';
/** @var string Uri user info. */
private $userInfo = '';
/** @var string Uri host. */
private $host = '';
/** @var int|null Uri port. */
private $port;
/** @var string Uri path. */
private $path = '';
/** @var string Uri query string. */
private $query = '';
/** @var string Uri fragment. */
private $fragment = '';
/**
* @param string $uri URI to parse
*/
public function __construct($uri = '')
{
// weak type check to also accept null until we can add scalar type hints
if ($uri != '') {
$parts = self::parse($uri);
if ($parts === false) {
throw new \InvalidArgumentException("Unable to parse URI: $uri");
}
$this->applyParts($parts);
}
}
/**
* UTF-8 aware \parse_url() replacement.
*
* The internal function produces broken output for non ASCII domain names
* (IDN) when used with locales other than "C".
*
* On the other hand, cURL understands IDN correctly only when UTF-8 locale
* is configured ("C.UTF-8", "en_US.UTF-8", etc.).
*
* @see https://bugs.php.net/bug.php?id=52923
* @see https://www.php.net/manual/en/function.parse-url.php#114817
* @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING
*
* @param string $url
*
* @return array|false
*/
private static function parse($url)
{
// If IPv6
$prefix = '';
if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) {
$prefix = $matches[1];
$url = $matches[2];
}
$encodedUrl = preg_replace_callback(
'%[^:/@?&=#]+%usD',
static function ($matches) {
return urlencode($matches[0]);
},
$url
);
$result = parse_url($prefix . $encodedUrl);
if ($result === false) {
return false;
}
return array_map('urldecode', $result);
}
public function __toString()
{
return self::composeComponents(
$this->scheme,
$this->getAuthority(),
$this->path,
$this->query,
$this->fragment
);
}
/**
* Composes a URI reference string from its various components.
*
* Usually this method does not need to be called manually but instead is used indirectly via
* `Psr\Http\Message\UriInterface::__toString`.
*
* PSR-7 UriInterface treats an empty component the same as a missing component as
* getQuery(), getFragment() etc. always return a string. This explains the slight
* difference to RFC 3986 Section 5.3.
*
* Another adjustment is that the authority separator is added even when the authority is missing/empty
* for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with
* `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But
* `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to
* that format).
*
* @param string $scheme
* @param string $authority
* @param string $path
* @param string $query
* @param string $fragment
*
* @return string
*
* @link https://tools.ietf.org/html/rfc3986#section-5.3
*/
public static function composeComponents($scheme, $authority, $path, $query, $fragment)
{
$uri = '';
// weak type checks to also accept null until we can add scalar type hints
if ($scheme != '') {
$uri .= $scheme . ':';
}
if ($authority != ''|| $scheme === 'file') {
$uri .= '//' . $authority;
}
$uri .= $path;
if ($query != '') {
$uri .= '?' . $query;
}
if ($fragment != '') {
$uri .= '#' . $fragment;
}
return $uri;
}
/**
* Whether the URI has the default port of the current scheme.
*
* `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used
* independently of the implementation.
*
* @param UriInterface $uri
*
* @return bool
*/
public static function isDefaultPort(UriInterface $uri)
{
return $uri->getPort() === null
|| (isset(self::$defaultPorts[$uri->getScheme()]) && $uri->getPort() === self::$defaultPorts[$uri->getScheme()]);
}
/**
* Whether the URI is absolute, i.e. it has a scheme.
*
* An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true
* if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative
* to another URI, the base URI. Relative references can be divided into several forms:
* - network-path references, e.g. '//example.com/path'
* - absolute-path references, e.g. '/path'
* - relative-path references, e.g. 'subpath'
*
* @param UriInterface $uri
*
* @return bool
*
* @see Uri::isNetworkPathReference
* @see Uri::isAbsolutePathReference
* @see Uri::isRelativePathReference
* @link https://tools.ietf.org/html/rfc3986#section-4
*/
public static function isAbsolute(UriInterface $uri)
{
return $uri->getScheme() !== '';
}
/**
* Whether the URI is a network-path reference.
*
* A relative reference that begins with two slash characters is termed an network-path reference.
*
* @param UriInterface $uri
*
* @return bool
*
* @link https://tools.ietf.org/html/rfc3986#section-4.2
*/
public static function isNetworkPathReference(UriInterface $uri)
{
return $uri->getScheme() === '' && $uri->getAuthority() !== '';
}
/**
* Whether the URI is a absolute-path reference.
*
* A relative reference that begins with a single slash character is termed an absolute-path reference.
*
* @param UriInterface $uri
*
* @return bool
*
* @link https://tools.ietf.org/html/rfc3986#section-4.2
*/
public static function isAbsolutePathReference(UriInterface $uri)
{
return $uri->getScheme() === ''
&& $uri->getAuthority() === ''
&& isset($uri->getPath()[0])
&& $uri->getPath()[0] === '/';
}
/**
* Whether the URI is a relative-path reference.
*
* A relative reference that does not begin with a slash character is termed a relative-path reference.
*
* @param UriInterface $uri
*
* @return bool
*
* @link https://tools.ietf.org/html/rfc3986#section-4.2
*/
public static function isRelativePathReference(UriInterface $uri)
{
return $uri->getScheme() === ''
&& $uri->getAuthority() === ''
&& (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/');
}
/**
* Whether the URI is a same-document reference.
*
* A same-document reference refers to a URI that is, aside from its fragment
* component, identical to the base URI. When no base URI is given, only an empty
* URI reference (apart from its fragment) is considered a same-document reference.
*
* @param UriInterface $uri The URI to check
* @param UriInterface|null $base An optional base URI to compare against
*
* @return bool
*
* @link https://tools.ietf.org/html/rfc3986#section-4.4
*/
public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null)
{
if ($base !== null) {
$uri = UriResolver::resolve($base, $uri);
return ($uri->getScheme() === $base->getScheme())
&& ($uri->getAuthority() === $base->getAuthority())
&& ($uri->getPath() === $base->getPath())
&& ($uri->getQuery() === $base->getQuery());
}
return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === '';
}
/**
* Removes dot segments from a path and returns the new path.
*
* @param string $path
*
* @return string
*
* @deprecated since version 1.4. Use UriResolver::removeDotSegments instead.
* @see UriResolver::removeDotSegments
*/
public static function removeDotSegments($path)
{
return UriResolver::removeDotSegments($path);
}
/**
* Converts the relative URI into a new URI that is resolved against the base URI.
*
* @param UriInterface $base Base URI
* @param string|UriInterface $rel Relative URI
*
* @return UriInterface
*
* @deprecated since version 1.4. Use UriResolver::resolve instead.
* @see UriResolver::resolve
*/
public static function resolve(UriInterface $base, $rel)
{
if (!($rel instanceof UriInterface)) {
$rel = new self($rel);
}
return UriResolver::resolve($base, $rel);
}
/**
* Creates a new URI with a specific query string value removed.
*
* Any existing query string values that exactly match the provided key are
* removed.
*
* @param UriInterface $uri URI to use as a base.
* @param string $key Query string key to remove.
*
* @return UriInterface
*/
public static function withoutQueryValue(UriInterface $uri, $key)
{
$result = self::getFilteredQueryString($uri, [$key]);
return $uri->withQuery(implode('&', $result));
}
/**
* Creates a new URI with a specific query string value.
*
* Any existing query string values that exactly match the provided key are
* removed and replaced with the given key value pair.
*
* A value of null will set the query string key without a value, e.g. "key"
* instead of "key=value".
*
* @param UriInterface $uri URI to use as a base.
* @param string $key Key to set.
* @param string|null $value Value to set
*
* @return UriInterface
*/
public static function withQueryValue(UriInterface $uri, $key, $value)
{
$result = self::getFilteredQueryString($uri, [$key]);
$result[] = self::generateQueryString($key, $value);
return $uri->withQuery(implode('&', $result));
}
/**
* Creates a new URI with multiple specific query string values.
*
* It has the same behavior as withQueryValue() but for an associative array of key => value.
*
* @param UriInterface $uri URI to use as a base.
* @param array $keyValueArray Associative array of key and values
*
* @return UriInterface
*/
public static function withQueryValues(UriInterface $uri, array $keyValueArray)
{
$result = self::getFilteredQueryString($uri, array_keys($keyValueArray));
foreach ($keyValueArray as $key => $value) {
$result[] = self::generateQueryString($key, $value);
}
return $uri->withQuery(implode('&', $result));
}
/**
* Creates a URI from a hash of `parse_url` components.
*
* @param array $parts
*
* @return UriInterface
*
* @link http://php.net/manual/en/function.parse-url.php
*
* @throws \InvalidArgumentException If the components do not form a valid URI.
*/
public static function fromParts(array $parts)
{
$uri = new self();
$uri->applyParts($parts);
$uri->validateState();
return $uri;
}
public function getScheme()
{
return $this->scheme;
}
public function getAuthority()
{
$authority = $this->host;
if ($this->userInfo !== '') {
$authority = $this->userInfo . '@' . $authority;
}
if ($this->port !== null) {
$authority .= ':' . $this->port;
}
return $authority;
}
public function getUserInfo()
{
return $this->userInfo;
}
public function getHost()
{
return $this->host;
}
public function getPort()
{
return $this->port;
}
public function getPath()
{
return $this->path;
}
public function getQuery()
{
return $this->query;
}
public function getFragment()
{
return $this->fragment;
}
public function withScheme($scheme)
{
$scheme = $this->filterScheme($scheme);
if ($this->scheme === $scheme) {
return $this;
}
$new = clone $this;
$new->scheme = $scheme;
$new->removeDefaultPort();
$new->validateState();
return $new;
}
public function withUserInfo($user, $password = null)
{
$info = $this->filterUserInfoComponent($user);
if ($password !== null) {
$info .= ':' . $this->filterUserInfoComponent($password);
}
if ($this->userInfo === $info) {
return $this;
}
$new = clone $this;
$new->userInfo = $info;
$new->validateState();
return $new;
}
public function withHost($host)
{
$host = $this->filterHost($host);
if ($this->host === $host) {
return $this;
}
$new = clone $this;
$new->host = $host;
$new->validateState();
return $new;
}
public function withPort($port)
{
$port = $this->filterPort($port);
if ($this->port === $port) {
return $this;
}
$new = clone $this;
$new->port = $port;
$new->removeDefaultPort();
$new->validateState();
return $new;
}
public function withPath($path)
{
$path = $this->filterPath($path);
if ($this->path === $path) {
return $this;
}
$new = clone $this;
$new->path = $path;
$new->validateState();
return $new;
}
public function withQuery($query)
{
$query = $this->filterQueryAndFragment($query);
if ($this->query === $query) {
return $this;
}
$new = clone $this;
$new->query = $query;
return $new;
}
public function withFragment($fragment)
{
$fragment = $this->filterQueryAndFragment($fragment);
if ($this->fragment === $fragment) {
return $this;
}
$new = clone $this;
$new->fragment = $fragment;
return $new;
}
/**
* Apply parse_url parts to a URI.
*
* @param array $parts Array of parse_url parts to apply.
*/
private function applyParts(array $parts)
{
$this->scheme = isset($parts['scheme'])
? $this->filterScheme($parts['scheme'])
: '';
$this->userInfo = isset($parts['user'])
? $this->filterUserInfoComponent($parts['user'])
: '';
$this->host = isset($parts['host'])
? $this->filterHost($parts['host'])
: '';
$this->port = isset($parts['port'])
? $this->filterPort($parts['port'])
: null;
$this->path = isset($parts['path'])
? $this->filterPath($parts['path'])
: '';
$this->query = isset($parts['query'])
? $this->filterQueryAndFragment($parts['query'])
: '';
$this->fragment = isset($parts['fragment'])
? $this->filterQueryAndFragment($parts['fragment'])
: '';
if (isset($parts['pass'])) {
$this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']);
}
$this->removeDefaultPort();
}
/**
* @param string $scheme
*
* @return string
*
* @throws \InvalidArgumentException If the scheme is invalid.
*/
private function filterScheme($scheme)
{
if (!is_string($scheme)) {
throw new \InvalidArgumentException('Scheme must be a string');
}
return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
}
/**
* @param string $component
*
* @return string
*
* @throws \InvalidArgumentException If the user info is invalid.
*/
private function filterUserInfoComponent($component)
{
if (!is_string($component)) {
throw new \InvalidArgumentException('User info must be a string');
}
return preg_replace_callback(
'/(?:[^%' . self::$charUnreserved . self::$charSubDelims . ']+|%(?![A-Fa-f0-9]{2}))/',
[$this, 'rawurlencodeMatchZero'],
$component
);
}
/**
* @param string $host
*
* @return string
*
* @throws \InvalidArgumentException If the host is invalid.
*/
private function filterHost($host)
{
if (!is_string($host)) {
throw new \InvalidArgumentException('Host must be a string');
}
return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
}
/**
* @param int|null $port
*
* @return int|null
*
* @throws \InvalidArgumentException If the port is invalid.
*/
private function filterPort($port)
{
if ($port === null) {
return null;
}
$port = (int) $port;
if (0 > $port || 0xffff < $port) {
throw new \InvalidArgumentException(
sprintf('Invalid port: %d. Must be between 0 and 65535', $port)
);
}
return $port;
}
/**
* @param UriInterface $uri
* @param array $keys
*
* @return array
*/
private static function getFilteredQueryString(UriInterface $uri, array $keys)
{
$current = $uri->getQuery();
if ($current === '') {
return [];
}
$decodedKeys = array_map('rawurldecode', $keys);
return array_filter(explode('&', $current), function ($part) use ($decodedKeys) {
return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true);
});
}
/**
* @param string $key
* @param string|null $value
*
* @return string
*/
private static function generateQueryString($key, $value)
{
// Query string separators ("=", "&") within the key or value need to be encoded
// (while preventing double-encoding) before setting the query string. All other
// chars that need percent-encoding will be encoded by withQuery().
$queryString = strtr($key, self::$replaceQuery);
if ($value !== null) {
$queryString .= '=' . strtr($value, self::$replaceQuery);
}
return $queryString;
}
private function removeDefaultPort()
{
if ($this->port !== null && self::isDefaultPort($this)) {
$this->port = null;
}
}
/**
* Filters the path of a URI
*
* @param string $path
*
* @return string
*
* @throws \InvalidArgumentException If the path is invalid.
*/
private function filterPath($path)
{
if (!is_string($path)) {
throw new \InvalidArgumentException('Path must be a string');
}
return preg_replace_callback(
'/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/',
[$this, 'rawurlencodeMatchZero'],
$path
);
}
/**
* Filters the query string or fragment of a URI.
*
* @param string $str
*
* @return string
*
* @throws \InvalidArgumentException If the query or fragment is invalid.
*/
private function filterQueryAndFragment($str)
{
if (!is_string($str)) {
throw new \InvalidArgumentException('Query and fragment must be a string');
}
return preg_replace_callback(
'/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
[$this, 'rawurlencodeMatchZero'],
$str
);
}
private function rawurlencodeMatchZero(array $match)
{
return rawurlencode($match[0]);
}
private function validateState()
{
if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) {
$this->host = self::HTTP_DEFAULT_HOST;
}
if ($this->getAuthority() === '') {
if (0 === strpos($this->path, '//')) {
throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"');
}
if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) {
throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon');
}
} elseif (isset($this->path[0]) && $this->path[0] !== '/') {
@trigger_error(
'The path of a URI with an authority must start with a slash "/" or be empty. Automagically fixing the URI ' .
'by adding a leading slash to the path is deprecated since version 1.4 and will throw an exception instead.',
E_USER_DEPRECATED
);
$this->path = '/' . $this->path;
//throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash "/" or be empty');
}
}
}

View File

@ -0,0 +1,55 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\UriInterface;
/**
* Provides methods to determine if a modified URL should be considered cross-origin.
*
* @author Graham Campbell
*/
final class UriComparator
{
/**
* Determines if a modified URL should be considered cross-origin with
* respect to an original URL.
*
* @return bool
*/
public static function isCrossOrigin(UriInterface $original, UriInterface $modified)
{
if (\strcasecmp($original->getHost(), $modified->getHost()) !== 0) {
return true;
}
if ($original->getScheme() !== $modified->getScheme()) {
return true;
}
if (self::computePort($original) !== self::computePort($modified)) {
return true;
}
return false;
}
/**
* @return int
*/
private static function computePort(UriInterface $uri)
{
$port = $uri->getPort();
if (null !== $port) {
return $port;
}
return 'https' === $uri->getScheme() ? 443 : 80;
}
private function __construct()
{
// cannot be instantiated
}
}

View File

@ -0,0 +1,219 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\UriInterface;
/**
* Provides methods to normalize and compare URIs.
*
* @author Tobias Schultze
*
* @link https://tools.ietf.org/html/rfc3986#section-6
*/
final class UriNormalizer
{
/**
* Default normalizations which only include the ones that preserve semantics.
*
* self::CAPITALIZE_PERCENT_ENCODING | self::DECODE_UNRESERVED_CHARACTERS | self::CONVERT_EMPTY_PATH |
* self::REMOVE_DEFAULT_HOST | self::REMOVE_DEFAULT_PORT | self::REMOVE_DOT_SEGMENTS
*/
const PRESERVING_NORMALIZATIONS = 63;
/**
* All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.
*
* Example: http://example.org/a%c2%b1b → http://example.org/a%C2%B1b
*/
const CAPITALIZE_PERCENT_ENCODING = 1;
/**
* Decodes percent-encoded octets of unreserved characters.
*
* For consistency, percent-encoded octets in the ranges of ALPHA (%41%5A and %61%7A), DIGIT (%30%39),
* hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should not be created by URI producers and,
* when found in a URI, should be decoded to their corresponding unreserved characters by URI normalizers.
*
* Example: http://example.org/%7Eusern%61me/ → http://example.org/~username/
*/
const DECODE_UNRESERVED_CHARACTERS = 2;
/**
* Converts the empty path to "/" for http and https URIs.
*
* Example: http://example.org → http://example.org/
*/
const CONVERT_EMPTY_PATH = 4;
/**
* Removes the default host of the given URI scheme from the URI.
*
* Only the "file" scheme defines the default host "localhost".
* All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile`
* are equivalent according to RFC 3986. The first format is not accepted
* by PHPs stream functions and thus already normalized implicitly to the
* second format in the Uri class. See `GuzzleHttp\Psr7\Uri::composeComponents`.
*
* Example: file://localhost/myfile → file:///myfile
*/
const REMOVE_DEFAULT_HOST = 8;
/**
* Removes the default port of the given URI scheme from the URI.
*
* Example: http://example.org:80/ → http://example.org/
*/
const REMOVE_DEFAULT_PORT = 16;
/**
* Removes unnecessary dot-segments.
*
* Dot-segments in relative-path references are not removed as it would
* change the semantics of the URI reference.
*
* Example: http://example.org/../a/b/../c/./d.html → http://example.org/a/c/d.html
*/
const REMOVE_DOT_SEGMENTS = 32;
/**
* Paths which include two or more adjacent slashes are converted to one.
*
* Webservers usually ignore duplicate slashes and treat those URIs equivalent.
* But in theory those URIs do not need to be equivalent. So this normalization
* may change the semantics. Encoded slashes (%2F) are not removed.
*
* Example: http://example.org//foo///bar.html → http://example.org/foo/bar.html
*/
const REMOVE_DUPLICATE_SLASHES = 64;
/**
* Sort query parameters with their values in alphabetical order.
*
* However, the order of parameters in a URI may be significant (this is not defined by the standard).
* So this normalization is not safe and may change the semantics of the URI.
*
* Example: ?lang=en&article=fred → ?article=fred&lang=en
*
* Note: The sorting is neither locale nor Unicode aware (the URI query does not get decoded at all) as the
* purpose is to be able to compare URIs in a reproducible way, not to have the params sorted perfectly.
*/
const SORT_QUERY_PARAMETERS = 128;
/**
* Returns a normalized URI.
*
* The scheme and host component are already normalized to lowercase per PSR-7 UriInterface.
* This methods adds additional normalizations that can be configured with the $flags parameter.
*
* PSR-7 UriInterface cannot distinguish between an empty component and a missing component as
* getQuery(), getFragment() etc. always return a string. This means the URIs "/?#" and "/" are
* treated equivalent which is not necessarily true according to RFC 3986. But that difference
* is highly uncommon in reality. So this potential normalization is implied in PSR-7 as well.
*
* @param UriInterface $uri The URI to normalize
* @param int $flags A bitmask of normalizations to apply, see constants
*
* @return UriInterface The normalized URI
*
* @link https://tools.ietf.org/html/rfc3986#section-6.2
*/
public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS)
{
if ($flags & self::CAPITALIZE_PERCENT_ENCODING) {
$uri = self::capitalizePercentEncoding($uri);
}
if ($flags & self::DECODE_UNRESERVED_CHARACTERS) {
$uri = self::decodeUnreservedCharacters($uri);
}
if ($flags & self::CONVERT_EMPTY_PATH && $uri->getPath() === '' &&
($uri->getScheme() === 'http' || $uri->getScheme() === 'https')
) {
$uri = $uri->withPath('/');
}
if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') {
$uri = $uri->withHost('');
}
if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) {
$uri = $uri->withPort(null);
}
if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) {
$uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath()));
}
if ($flags & self::REMOVE_DUPLICATE_SLASHES) {
$uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath()));
}
if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') {
$queryKeyValues = explode('&', $uri->getQuery());
sort($queryKeyValues);
$uri = $uri->withQuery(implode('&', $queryKeyValues));
}
return $uri;
}
/**
* Whether two URIs can be considered equivalent.
*
* Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also
* accepts relative URI references and returns true when they are equivalent. This of course assumes they will be
* resolved against the same base URI. If this is not the case, determination of equivalence or difference of
* relative references does not mean anything.
*
* @param UriInterface $uri1 An URI to compare
* @param UriInterface $uri2 An URI to compare
* @param int $normalizations A bitmask of normalizations to apply, see constants
*
* @return bool
*
* @link https://tools.ietf.org/html/rfc3986#section-6.1
*/
public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS)
{
return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations);
}
private static function capitalizePercentEncoding(UriInterface $uri)
{
$regex = '/(?:%[A-Fa-f0-9]{2})++/';
$callback = function (array $match) {
return strtoupper($match[0]);
};
return
$uri->withPath(
preg_replace_callback($regex, $callback, $uri->getPath())
)->withQuery(
preg_replace_callback($regex, $callback, $uri->getQuery())
);
}
private static function decodeUnreservedCharacters(UriInterface $uri)
{
$regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i';
$callback = function (array $match) {
return rawurldecode($match[0]);
};
return
$uri->withPath(
preg_replace_callback($regex, $callback, $uri->getPath())
)->withQuery(
preg_replace_callback($regex, $callback, $uri->getQuery())
);
}
private function __construct()
{
// cannot be instantiated
}
}

View File

@ -0,0 +1,222 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\UriInterface;
/**
* Resolves a URI reference in the context of a base URI and the opposite way.
*
* @author Tobias Schultze
*
* @link https://tools.ietf.org/html/rfc3986#section-5
*/
final class UriResolver
{
/**
* Removes dot segments from a path and returns the new path.
*
* @param string $path
*
* @return string
*
* @link http://tools.ietf.org/html/rfc3986#section-5.2.4
*/
public static function removeDotSegments($path)
{
if ($path === '' || $path === '/') {
return $path;
}
$results = [];
$segments = explode('/', $path);
foreach ($segments as $segment) {
if ($segment === '..') {
array_pop($results);
} elseif ($segment !== '.') {
$results[] = $segment;
}
}
$newPath = implode('/', $results);
if ($path[0] === '/' && (!isset($newPath[0]) || $newPath[0] !== '/')) {
// Re-add the leading slash if necessary for cases like "/.."
$newPath = '/' . $newPath;
} elseif ($newPath !== '' && ($segment === '.' || $segment === '..')) {
// Add the trailing slash if necessary
// If newPath is not empty, then $segment must be set and is the last segment from the foreach
$newPath .= '/';
}
return $newPath;
}
/**
* Converts the relative URI into a new URI that is resolved against the base URI.
*
* @param UriInterface $base Base URI
* @param UriInterface $rel Relative URI
*
* @return UriInterface
*
* @link http://tools.ietf.org/html/rfc3986#section-5.2
*/
public static function resolve(UriInterface $base, UriInterface $rel)
{
if ((string) $rel === '') {
// we can simply return the same base URI instance for this same-document reference
return $base;
}
if ($rel->getScheme() != '') {
return $rel->withPath(self::removeDotSegments($rel->getPath()));
}
if ($rel->getAuthority() != '') {
$targetAuthority = $rel->getAuthority();
$targetPath = self::removeDotSegments($rel->getPath());
$targetQuery = $rel->getQuery();
} else {
$targetAuthority = $base->getAuthority();
if ($rel->getPath() === '') {
$targetPath = $base->getPath();
$targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery();
} else {
if ($rel->getPath()[0] === '/') {
$targetPath = $rel->getPath();
} else {
if ($targetAuthority != '' && $base->getPath() === '') {
$targetPath = '/' . $rel->getPath();
} else {
$lastSlashPos = strrpos($base->getPath(), '/');
if ($lastSlashPos === false) {
$targetPath = $rel->getPath();
} else {
$targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath();
}
}
}
$targetPath = self::removeDotSegments($targetPath);
$targetQuery = $rel->getQuery();
}
}
return new Uri(Uri::composeComponents(
$base->getScheme(),
$targetAuthority,
$targetPath,
$targetQuery,
$rel->getFragment()
));
}
/**
* Returns the target URI as a relative reference from the base URI.
*
* This method is the counterpart to resolve():
*
* (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))
*
* One use-case is to use the current request URI as base URI and then generate relative links in your documents
* to reduce the document size or offer self-contained downloadable document archives.
*
* $base = new Uri('http://example.com/a/b/');
* echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'.
* echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'.
* echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
* echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'.
*
* This method also accepts a target that is already relative and will try to relativize it further. Only a
* relative-path reference will be returned as-is.
*
* echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well
*
* @param UriInterface $base Base URI
* @param UriInterface $target Target URI
*
* @return UriInterface The relative URI reference
*/
public static function relativize(UriInterface $base, UriInterface $target)
{
if ($target->getScheme() !== '' &&
($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '')
) {
return $target;
}
if (Uri::isRelativePathReference($target)) {
// As the target is already highly relative we return it as-is. It would be possible to resolve
// the target with `$target = self::resolve($base, $target);` and then try make it more relative
// by removing a duplicate query. But let's not do that automatically.
return $target;
}
if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) {
return $target->withScheme('');
}
// We must remove the path before removing the authority because if the path starts with two slashes, the URI
// would turn invalid. And we also cannot set a relative path before removing the authority, as that is also
// invalid.
$emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost('');
if ($base->getPath() !== $target->getPath()) {
return $emptyPathUri->withPath(self::getRelativePath($base, $target));
}
if ($base->getQuery() === $target->getQuery()) {
// Only the target fragment is left. And it must be returned even if base and target fragment are the same.
return $emptyPathUri->withQuery('');
}
// If the base URI has a query but the target has none, we cannot return an empty path reference as it would
// inherit the base query component when resolving.
if ($target->getQuery() === '') {
$segments = explode('/', $target->getPath());
$lastSegment = end($segments);
return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment);
}
return $emptyPathUri;
}
private static function getRelativePath(UriInterface $base, UriInterface $target)
{
$sourceSegments = explode('/', $base->getPath());
$targetSegments = explode('/', $target->getPath());
array_pop($sourceSegments);
$targetLastSegment = array_pop($targetSegments);
foreach ($sourceSegments as $i => $segment) {
if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) {
unset($sourceSegments[$i], $targetSegments[$i]);
} else {
break;
}
}
$targetSegments[] = $targetLastSegment;
$relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments);
// A reference to am empty last segment or an empty first sub-segment must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
// as the first segment of a relative-path reference, as it would be mistaken for a scheme name.
if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) {
$relativePath = "./$relativePath";
} elseif ('/' === $relativePath[0]) {
if ($base->getAuthority() != '' && $base->getPath() === '') {
// In this case an extra slash is added by resolve() automatically. So we must not add one here.
$relativePath = ".$relativePath";
} else {
$relativePath = "./$relativePath";
}
}
return $relativePath;
}
private function __construct()
{
// cannot be instantiated
}
}

View File

@ -0,0 +1,428 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
final class Utils
{
/**
* Remove the items given by the keys, case insensitively from the data.
*
* @param iterable<string> $keys
*
* @return array
*/
public static function caselessRemove($keys, array $data)
{
$result = [];
foreach ($keys as &$key) {
$key = strtolower($key);
}
foreach ($data as $k => $v) {
if (!in_array(strtolower($k), $keys)) {
$result[$k] = $v;
}
}
return $result;
}
/**
* Copy the contents of a stream into another stream until the given number
* of bytes have been read.
*
* @param StreamInterface $source Stream to read from
* @param StreamInterface $dest Stream to write to
* @param int $maxLen Maximum number of bytes to read. Pass -1
* to read the entire stream.
*
* @throws \RuntimeException on error.
*/
public static function copyToStream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)
{
$bufferSize = 8192;
if ($maxLen === -1) {
while (!$source->eof()) {
if (!$dest->write($source->read($bufferSize))) {
break;
}
}
} else {
$remaining = $maxLen;
while ($remaining > 0 && !$source->eof()) {
$buf = $source->read(min($bufferSize, $remaining));
$len = strlen($buf);
if (!$len) {
break;
}
$remaining -= $len;
$dest->write($buf);
}
}
}
/**
* Copy the contents of a stream into a string until the given number of
* bytes have been read.
*
* @param StreamInterface $stream Stream to read
* @param int $maxLen Maximum number of bytes to read. Pass -1
* to read the entire stream.
*
* @return string
*
* @throws \RuntimeException on error.
*/
public static function copyToString(StreamInterface $stream, $maxLen = -1)
{
$buffer = '';
if ($maxLen === -1) {
while (!$stream->eof()) {
$buf = $stream->read(1048576);
// Using a loose equality here to match on '' and false.
if ($buf == null) {
break;
}
$buffer .= $buf;
}
return $buffer;
}
$len = 0;
while (!$stream->eof() && $len < $maxLen) {
$buf = $stream->read($maxLen - $len);
// Using a loose equality here to match on '' and false.
if ($buf == null) {
break;
}
$buffer .= $buf;
$len = strlen($buffer);
}
return $buffer;
}
/**
* Calculate a hash of a stream.
*
* This method reads the entire stream to calculate a rolling hash, based
* on PHP's `hash_init` functions.
*
* @param StreamInterface $stream Stream to calculate the hash for
* @param string $algo Hash algorithm (e.g. md5, crc32, etc)
* @param bool $rawOutput Whether or not to use raw output
*
* @return string Returns the hash of the stream
*
* @throws \RuntimeException on error.
*/
public static function hash(StreamInterface $stream, $algo, $rawOutput = false)
{
$pos = $stream->tell();
if ($pos > 0) {
$stream->rewind();
}
$ctx = hash_init($algo);
while (!$stream->eof()) {
hash_update($ctx, $stream->read(1048576));
}
$out = hash_final($ctx, (bool) $rawOutput);
$stream->seek($pos);
return $out;
}
/**
* Clone and modify a request with the given changes.
*
* This method is useful for reducing the number of clones needed to mutate
* a message.
*
* The changes can be one of:
* - method: (string) Changes the HTTP method.
* - set_headers: (array) Sets the given headers.
* - remove_headers: (array) Remove the given headers.
* - body: (mixed) Sets the given body.
* - uri: (UriInterface) Set the URI.
* - query: (string) Set the query string value of the URI.
* - version: (string) Set the protocol version.
*
* @param RequestInterface $request Request to clone and modify.
* @param array $changes Changes to apply.
*
* @return RequestInterface
*/
public static function modifyRequest(RequestInterface $request, array $changes)
{
if (!$changes) {
return $request;
}
$headers = $request->getHeaders();
if (!isset($changes['uri'])) {
$uri = $request->getUri();
} else {
// Remove the host header if one is on the URI
if ($host = $changes['uri']->getHost()) {
$changes['set_headers']['Host'] = $host;
if ($port = $changes['uri']->getPort()) {
$standardPorts = ['http' => 80, 'https' => 443];
$scheme = $changes['uri']->getScheme();
if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) {
$changes['set_headers']['Host'] .= ':' . $port;
}
}
}
$uri = $changes['uri'];
}
if (!empty($changes['remove_headers'])) {
$headers = self::caselessRemove($changes['remove_headers'], $headers);
}
if (!empty($changes['set_headers'])) {
$headers = self::caselessRemove(array_keys($changes['set_headers']), $headers);
$headers = $changes['set_headers'] + $headers;
}
if (isset($changes['query'])) {
$uri = $uri->withQuery($changes['query']);
}
if ($request instanceof ServerRequestInterface) {
$new = (new ServerRequest(
isset($changes['method']) ? $changes['method'] : $request->getMethod(),
$uri,
$headers,
isset($changes['body']) ? $changes['body'] : $request->getBody(),
isset($changes['version'])
? $changes['version']
: $request->getProtocolVersion(),
$request->getServerParams()
))
->withParsedBody($request->getParsedBody())
->withQueryParams($request->getQueryParams())
->withCookieParams($request->getCookieParams())
->withUploadedFiles($request->getUploadedFiles());
foreach ($request->getAttributes() as $key => $value) {
$new = $new->withAttribute($key, $value);
}
return $new;
}
return new Request(
isset($changes['method']) ? $changes['method'] : $request->getMethod(),
$uri,
$headers,
isset($changes['body']) ? $changes['body'] : $request->getBody(),
isset($changes['version'])
? $changes['version']
: $request->getProtocolVersion()
);
}
/**
* Read a line from the stream up to the maximum allowed buffer length.
*
* @param StreamInterface $stream Stream to read from
* @param int|null $maxLength Maximum buffer length
*
* @return string
*/
public static function readLine(StreamInterface $stream, $maxLength = null)
{
$buffer = '';
$size = 0;
while (!$stream->eof()) {
// Using a loose equality here to match on '' and false.
if (null == ($byte = $stream->read(1))) {
return $buffer;
}
$buffer .= $byte;
// Break when a new line is found or the max length - 1 is reached
if ($byte === "\n" || ++$size === $maxLength - 1) {
break;
}
}
return $buffer;
}
/**
* Create a new stream based on the input type.
*
* Options is an associative array that can contain the following keys:
* - metadata: Array of custom metadata.
* - size: Size of the stream.
*
* This method accepts the following `$resource` types:
* - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
* - `string`: Creates a stream object that uses the given string as the contents.
* - `resource`: Creates a stream object that wraps the given PHP stream resource.
* - `Iterator`: If the provided value implements `Iterator`, then a read-only
* stream object will be created that wraps the given iterable. Each time the
* stream is read from, data from the iterator will fill a buffer and will be
* continuously called until the buffer is equal to the requested read size.
* Subsequent read calls will first read from the buffer and then call `next`
* on the underlying iterator until it is exhausted.
* - `object` with `__toString()`: If the object has the `__toString()` method,
* the object will be cast to a string and then a stream will be returned that
* uses the string value.
* - `NULL`: When `null` is passed, an empty stream object is returned.
* - `callable` When a callable is passed, a read-only stream object will be
* created that invokes the given callable. The callable is invoked with the
* number of suggested bytes to read. The callable can return any number of
* bytes, but MUST return `false` when there is no more data to return. The
* stream object that wraps the callable will invoke the callable until the
* number of requested bytes are available. Any additional bytes will be
* buffered and used in subsequent reads.
*
* @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
* @param array $options Additional options
*
* @return StreamInterface
*
* @throws \InvalidArgumentException if the $resource arg is not valid.
*/
public static function streamFor($resource = '', array $options = [])
{
if (is_scalar($resource)) {
$stream = self::tryFopen('php://temp', 'r+');
if ($resource !== '') {
fwrite($stream, $resource);
fseek($stream, 0);
}
return new Stream($stream, $options);
}
switch (gettype($resource)) {
case 'resource':
/*
* The 'php://input' is a special stream with quirks and inconsistencies.
* We avoid using that stream by reading it into php://temp
*/
$metaData = \stream_get_meta_data($resource);
if (isset($metaData['uri']) && $metaData['uri'] === 'php://input') {
$stream = self::tryFopen('php://temp', 'w+');
fwrite($stream, stream_get_contents($resource));
fseek($stream, 0);
$resource = $stream;
}
return new Stream($resource, $options);
case 'object':
if ($resource instanceof StreamInterface) {
return $resource;
} elseif ($resource instanceof \Iterator) {
return new PumpStream(function () use ($resource) {
if (!$resource->valid()) {
return false;
}
$result = $resource->current();
$resource->next();
return $result;
}, $options);
} elseif (method_exists($resource, '__toString')) {
return Utils::streamFor((string) $resource, $options);
}
break;
case 'NULL':
return new Stream(self::tryFopen('php://temp', 'r+'), $options);
}
if (is_callable($resource)) {
return new PumpStream($resource, $options);
}
throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource));
}
/**
* Safely opens a PHP stream resource using a filename.
*
* When fopen fails, PHP normally raises a warning. This function adds an
* error handler that checks for errors and throws an exception instead.
*
* @param string $filename File to open
* @param string $mode Mode used to open the file
*
* @return resource
*
* @throws \RuntimeException if the file cannot be opened
*/
public static function tryFopen($filename, $mode)
{
$ex = null;
set_error_handler(function () use ($filename, $mode, &$ex) {
$ex = new \RuntimeException(sprintf(
'Unable to open "%s" using mode "%s": %s',
$filename,
$mode,
func_get_args()[1]
));
return true;
});
try {
$handle = fopen($filename, $mode);
} catch (\Throwable $e) {
$ex = new \RuntimeException(sprintf(
'Unable to open "%s" using mode "%s": %s',
$filename,
$mode,
$e->getMessage()
), 0, $e);
}
restore_error_handler();
if ($ex) {
/** @var $ex \RuntimeException */
throw $ex;
}
return $handle;
}
/**
* Returns a UriInterface for the given value.
*
* This function accepts a string or UriInterface and returns a
* UriInterface for the given value. If the value is already a
* UriInterface, it is returned as-is.
*
* @param string|UriInterface $uri
*
* @return UriInterface
*
* @throws \InvalidArgumentException
*/
public static function uriFor($uri)
{
if ($uri instanceof UriInterface) {
return $uri;
}
if (is_string($uri)) {
return new Uri($uri);
}
throw new \InvalidArgumentException('URI must be a string or UriInterface');
}
}

View File

@ -0,0 +1,422 @@
<?php
namespace GuzzleHttp\Psr7;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
/**
* Returns the string representation of an HTTP message.
*
* @param MessageInterface $message Message to convert to a string.
*
* @return string
*
* @deprecated str will be removed in guzzlehttp/psr7:2.0. Use Message::toString instead.
*/
function str(MessageInterface $message)
{
return Message::toString($message);
}
/**
* Returns a UriInterface for the given value.
*
* This function accepts a string or UriInterface and returns a
* UriInterface for the given value. If the value is already a
* UriInterface, it is returned as-is.
*
* @param string|UriInterface $uri
*
* @return UriInterface
*
* @throws \InvalidArgumentException
*
* @deprecated uri_for will be removed in guzzlehttp/psr7:2.0. Use Utils::uriFor instead.
*/
function uri_for($uri)
{
return Utils::uriFor($uri);
}
/**
* Create a new stream based on the input type.
*
* Options is an associative array that can contain the following keys:
* - metadata: Array of custom metadata.
* - size: Size of the stream.
*
* This method accepts the following `$resource` types:
* - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
* - `string`: Creates a stream object that uses the given string as the contents.
* - `resource`: Creates a stream object that wraps the given PHP stream resource.
* - `Iterator`: If the provided value implements `Iterator`, then a read-only
* stream object will be created that wraps the given iterable. Each time the
* stream is read from, data from the iterator will fill a buffer and will be
* continuously called until the buffer is equal to the requested read size.
* Subsequent read calls will first read from the buffer and then call `next`
* on the underlying iterator until it is exhausted.
* - `object` with `__toString()`: If the object has the `__toString()` method,
* the object will be cast to a string and then a stream will be returned that
* uses the string value.
* - `NULL`: When `null` is passed, an empty stream object is returned.
* - `callable` When a callable is passed, a read-only stream object will be
* created that invokes the given callable. The callable is invoked with the
* number of suggested bytes to read. The callable can return any number of
* bytes, but MUST return `false` when there is no more data to return. The
* stream object that wraps the callable will invoke the callable until the
* number of requested bytes are available. Any additional bytes will be
* buffered and used in subsequent reads.
*
* @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
* @param array $options Additional options
*
* @return StreamInterface
*
* @throws \InvalidArgumentException if the $resource arg is not valid.
*
* @deprecated stream_for will be removed in guzzlehttp/psr7:2.0. Use Utils::streamFor instead.
*/
function stream_for($resource = '', array $options = [])
{
return Utils::streamFor($resource, $options);
}
/**
* Parse an array of header values containing ";" separated data into an
* array of associative arrays representing the header key value pair data
* of the header. When a parameter does not contain a value, but just
* contains a key, this function will inject a key with a '' string value.
*
* @param string|array $header Header to parse into components.
*
* @return array Returns the parsed header values.
*
* @deprecated parse_header will be removed in guzzlehttp/psr7:2.0. Use Header::parse instead.
*/
function parse_header($header)
{
return Header::parse($header);
}
/**
* Converts an array of header values that may contain comma separated
* headers into an array of headers with no comma separated values.
*
* @param string|array $header Header to normalize.
*
* @return array Returns the normalized header field values.
*
* @deprecated normalize_header will be removed in guzzlehttp/psr7:2.0. Use Header::normalize instead.
*/
function normalize_header($header)
{
return Header::normalize($header);
}
/**
* Clone and modify a request with the given changes.
*
* This method is useful for reducing the number of clones needed to mutate a
* message.
*
* The changes can be one of:
* - method: (string) Changes the HTTP method.
* - set_headers: (array) Sets the given headers.
* - remove_headers: (array) Remove the given headers.
* - body: (mixed) Sets the given body.
* - uri: (UriInterface) Set the URI.
* - query: (string) Set the query string value of the URI.
* - version: (string) Set the protocol version.
*
* @param RequestInterface $request Request to clone and modify.
* @param array $changes Changes to apply.
*
* @return RequestInterface
*
* @deprecated modify_request will be removed in guzzlehttp/psr7:2.0. Use Utils::modifyRequest instead.
*/
function modify_request(RequestInterface $request, array $changes)
{
return Utils::modifyRequest($request, $changes);
}
/**
* Attempts to rewind a message body and throws an exception on failure.
*
* The body of the message will only be rewound if a call to `tell()` returns a
* value other than `0`.
*
* @param MessageInterface $message Message to rewind
*
* @throws \RuntimeException
*
* @deprecated rewind_body will be removed in guzzlehttp/psr7:2.0. Use Message::rewindBody instead.
*/
function rewind_body(MessageInterface $message)
{
Message::rewindBody($message);
}
/**
* Safely opens a PHP stream resource using a filename.
*
* When fopen fails, PHP normally raises a warning. This function adds an
* error handler that checks for errors and throws an exception instead.
*
* @param string $filename File to open
* @param string $mode Mode used to open the file
*
* @return resource
*
* @throws \RuntimeException if the file cannot be opened
*
* @deprecated try_fopen will be removed in guzzlehttp/psr7:2.0. Use Utils::tryFopen instead.
*/
function try_fopen($filename, $mode)
{
return Utils::tryFopen($filename, $mode);
}
/**
* Copy the contents of a stream into a string until the given number of
* bytes have been read.
*
* @param StreamInterface $stream Stream to read
* @param int $maxLen Maximum number of bytes to read. Pass -1
* to read the entire stream.
*
* @return string
*
* @throws \RuntimeException on error.
*
* @deprecated copy_to_string will be removed in guzzlehttp/psr7:2.0. Use Utils::copyToString instead.
*/
function copy_to_string(StreamInterface $stream, $maxLen = -1)
{
return Utils::copyToString($stream, $maxLen);
}
/**
* Copy the contents of a stream into another stream until the given number
* of bytes have been read.
*
* @param StreamInterface $source Stream to read from
* @param StreamInterface $dest Stream to write to
* @param int $maxLen Maximum number of bytes to read. Pass -1
* to read the entire stream.
*
* @throws \RuntimeException on error.
*
* @deprecated copy_to_stream will be removed in guzzlehttp/psr7:2.0. Use Utils::copyToStream instead.
*/
function copy_to_stream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)
{
return Utils::copyToStream($source, $dest, $maxLen);
}
/**
* Calculate a hash of a stream.
*
* This method reads the entire stream to calculate a rolling hash, based on
* PHP's `hash_init` functions.
*
* @param StreamInterface $stream Stream to calculate the hash for
* @param string $algo Hash algorithm (e.g. md5, crc32, etc)
* @param bool $rawOutput Whether or not to use raw output
*
* @return string Returns the hash of the stream
*
* @throws \RuntimeException on error.
*
* @deprecated hash will be removed in guzzlehttp/psr7:2.0. Use Utils::hash instead.
*/
function hash(StreamInterface $stream, $algo, $rawOutput = false)
{
return Utils::hash($stream, $algo, $rawOutput);
}
/**
* Read a line from the stream up to the maximum allowed buffer length.
*
* @param StreamInterface $stream Stream to read from
* @param int|null $maxLength Maximum buffer length
*
* @return string
*
* @deprecated readline will be removed in guzzlehttp/psr7:2.0. Use Utils::readLine instead.
*/
function readline(StreamInterface $stream, $maxLength = null)
{
return Utils::readLine($stream, $maxLength);
}
/**
* Parses a request message string into a request object.
*
* @param string $message Request message string.
*
* @return Request
*
* @deprecated parse_request will be removed in guzzlehttp/psr7:2.0. Use Message::parseRequest instead.
*/
function parse_request($message)
{
return Message::parseRequest($message);
}
/**
* Parses a response message string into a response object.
*
* @param string $message Response message string.
*
* @return Response
*
* @deprecated parse_response will be removed in guzzlehttp/psr7:2.0. Use Message::parseResponse instead.
*/
function parse_response($message)
{
return Message::parseResponse($message);
}
/**
* Parse a query string into an associative array.
*
* If multiple values are found for the same key, the value of that key value
* pair will become an array. This function does not parse nested PHP style
* arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` will be parsed
* into `['foo[a]' => '1', 'foo[b]' => '2'])`.
*
* @param string $str Query string to parse
* @param int|bool $urlEncoding How the query string is encoded
*
* @return array
*
* @deprecated parse_query will be removed in guzzlehttp/psr7:2.0. Use Query::parse instead.
*/
function parse_query($str, $urlEncoding = true)
{
return Query::parse($str, $urlEncoding);
}
/**
* Build a query string from an array of key value pairs.
*
* This function can use the return value of `parse_query()` to build a query
* string. This function does not modify the provided keys when an array is
* encountered (like `http_build_query()` would).
*
* @param array $params Query string parameters.
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
* to encode using RFC3986, or PHP_QUERY_RFC1738
* to encode using RFC1738.
*
* @return string
*
* @deprecated build_query will be removed in guzzlehttp/psr7:2.0. Use Query::build instead.
*/
function build_query(array $params, $encoding = PHP_QUERY_RFC3986)
{
return Query::build($params, $encoding);
}
/**
* Determines the mimetype of a file by looking at its extension.
*
* @param string $filename
*
* @return string|null
*
* @deprecated mimetype_from_filename will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromFilename instead.
*/
function mimetype_from_filename($filename)
{
return MimeType::fromFilename($filename);
}
/**
* Maps a file extensions to a mimetype.
*
* @param $extension string The file extension.
*
* @return string|null
*
* @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
* @deprecated mimetype_from_extension will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromExtension instead.
*/
function mimetype_from_extension($extension)
{
return MimeType::fromExtension($extension);
}
/**
* Parses an HTTP message into an associative array.
*
* The array contains the "start-line" key containing the start line of
* the message, "headers" key containing an associative array of header
* array values, and a "body" key containing the body of the message.
*
* @param string $message HTTP request or response to parse.
*
* @return array
*
* @internal
*
* @deprecated _parse_message will be removed in guzzlehttp/psr7:2.0. Use Message::parseMessage instead.
*/
function _parse_message($message)
{
return Message::parseMessage($message);
}
/**
* Constructs a URI for an HTTP request message.
*
* @param string $path Path from the start-line
* @param array $headers Array of headers (each value an array).
*
* @return string
*
* @internal
*
* @deprecated _parse_request_uri will be removed in guzzlehttp/psr7:2.0. Use Message::parseRequestUri instead.
*/
function _parse_request_uri($path, array $headers)
{
return Message::parseRequestUri($path, $headers);
}
/**
* Get a short summary of the message body.
*
* Will return `null` if the response is not printable.
*
* @param MessageInterface $message The message to get the body summary
* @param int $truncateAt The maximum allowed size of the summary
*
* @return string|null
*
* @deprecated get_message_body_summary will be removed in guzzlehttp/psr7:2.0. Use Message::bodySummary instead.
*/
function get_message_body_summary(MessageInterface $message, $truncateAt = 120)
{
return Message::bodySummary($message, $truncateAt);
}
/**
* Remove the items given by the keys, case insensitively from the data.
*
* @param iterable<string> $keys
*
* @return array
*
* @internal
*
* @deprecated _caseless_remove will be removed in guzzlehttp/psr7:2.0. Use Utils::caselessRemove instead.
*/
function _caseless_remove($keys, array $data)
{
return Utils::caselessRemove($keys, $data);
}

View File

@ -0,0 +1,6 @@
<?php
// Don't redefine the functions if included multiple times.
if (!function_exists('GuzzleHttp\Psr7\str')) {
require __DIR__ . '/functions.php';
}

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);
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
class HasToString
{
public function __toString()
{
return 'foo';
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
class HeaderTest extends BaseTest
{
public function parseParamsProvider()
{
$res1 = [
[
'<http:/.../front.jpeg>',
'rel' => 'front',
'type' => 'image/jpeg',
],
[
'<http://.../back.jpeg>',
'rel' => 'back',
'type' => 'image/jpeg',
],
];
return [
[
'<http:/.../front.jpeg>; rel="front"; type="image/jpeg", <http://.../back.jpeg>; rel=back; type="image/jpeg"',
$res1,
],
[
'<http:/.../front.jpeg>; rel="front"; type="image/jpeg",<http://.../back.jpeg>; rel=back; type="image/jpeg"',
$res1,
],
[
'foo="baz"; bar=123, boo, test="123", foobar="foo;bar"',
[
['foo' => 'baz', 'bar' => '123'],
['boo'],
['test' => '123'],
['foobar' => 'foo;bar'],
],
],
[
'<http://.../side.jpeg?test=1>; rel="side"; type="image/jpeg",<http://.../side.jpeg?test=2>; rel=side; type="image/jpeg"',
[
['<http://.../side.jpeg?test=1>', 'rel' => 'side', 'type' => 'image/jpeg'],
['<http://.../side.jpeg?test=2>', 'rel' => 'side', 'type' => 'image/jpeg'],
],
],
[
'',
[],
],
];
}
/**
* @dataProvider parseParamsProvider
*/
public function testParseParams($header, $result)
{
self::assertSame($result, Psr7\Header::parse($header));
}
public function testParsesArrayHeaders()
{
$header = ['a, b', 'c', 'd, e'];
self::assertSame(['a', 'b', 'c', 'd', 'e'], Psr7\Header::normalize($header));
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
class Helpers
{
/**
* @param object $object
* @param string $attributeName
*/
public static function readObjectAttribute($object, $attributeName)
{
$reflector = new \ReflectionObject($object);
do {
try {
$attribute = $reflector->getProperty($attributeName);
if (!$attribute || $attribute->isPublic()) {
return $object->$attributeName;
}
$attribute->setAccessible(true);
return $attribute->getValue($object);
} catch (\ReflectionException $e) {
// do nothing
}
} while ($reflector = $reflector->getParentClass());
throw new \Exception(
sprintf('Attribute "%s" not found in object.', $attributeName)
);
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\InflateStream;
use GuzzleHttp\Psr7\NoSeekStream;
class InflateStreamTest extends BaseTest
{
public function testInflatesStreams()
{
$content = gzencode('test');
$a = Psr7\Utils::streamFor($content);
$b = new InflateStream($a);
self::assertSame('test', (string) $b);
}
public function testInflatesStreamsWithFilename()
{
$content = $this->getGzipStringWithFilename('test');
$a = Psr7\Utils::streamFor($content);
$b = new InflateStream($a);
self::assertSame('test', (string) $b);
}
public function testInflatesStreamsPreserveSeekable()
{
$content = $this->getGzipStringWithFilename('test');
$seekable = Psr7\Utils::streamFor($content);
$nonSeekable = new NoSeekStream(Psr7\Utils::streamFor($content));
self::assertTrue((new InflateStream($seekable))->isSeekable());
self::assertFalse((new InflateStream($nonSeekable))->isSeekable());
}
private function getGzipStringWithFilename($original_string)
{
$gzipped = bin2hex(gzencode($original_string));
$header = substr($gzipped, 0, 20);
// set FNAME flag
$header[6]=0;
$header[7]=8;
// make a dummy filename
$filename = '64756d6d7900';
$rest = substr($gzipped, 20);
return hex2bin($header . $filename . $rest);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace GuzzleHttp\Tests\Psr7\Integration;
use GuzzleHttp\Tests\Psr7\BaseTest;
class ServerRequestFromGlobalsTest extends BaseTest
{
/**
* @before
*/
protected function setUpTest()
{
if (false === $this->getServerUri()) {
self::markTestSkipped();
}
parent::setUp();
}
public function testBodyExists()
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->getServerUri());
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'foobar');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
self::assertNotFalse($response);
$data = json_decode($response, true);
self::assertIsArray($data);
self::assertArrayHasKey('method', $data);
self::assertArrayHasKey('uri', $data);
self::assertArrayHasKey('body', $data);
self::assertEquals('foobar', $data['body']);
}
private function getServerUri()
{
return isset($_SERVER['TEST_SERVER']) ? $_SERVER['TEST_SERVER'] : false;
}
}

View File

@ -0,0 +1,13 @@
<?php
require dirname(__DIR__, 2) . '/vendor/autoload.php';
$request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
$output = [
'method' => $request->getMethod(),
'uri' => $request->getUri()->__toString(),
'body' => $request->getBody()->__toString(),
];
echo json_encode($output);

View File

@ -0,0 +1,71 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\LazyOpenStream;
class LazyOpenStreamTest extends BaseTest
{
private $fname;
/**
* @before
*/
public function setUpTest()
{
$this->fname = tempnam(sys_get_temp_dir(), 'tfile');
if (file_exists($this->fname)) {
unlink($this->fname);
}
}
/**
* @after
*/
public function tearDownTest()
{
if (file_exists($this->fname)) {
unlink($this->fname);
}
}
public function testOpensLazily()
{
$l = new LazyOpenStream($this->fname, 'w+');
$l->write('foo');
$this->assertInternalTypeGuzzle('array', $l->getMetadata());
self::assertFileExists($this->fname);
self::assertSame('foo', file_get_contents($this->fname));
self::assertSame('foo', (string) $l);
}
public function testProxiesToFile()
{
file_put_contents($this->fname, 'foo');
$l = new LazyOpenStream($this->fname, 'r');
self::assertSame('foo', $l->read(4));
self::assertTrue($l->eof());
self::assertSame(3, $l->tell());
self::assertTrue($l->isReadable());
self::assertTrue($l->isSeekable());
self::assertFalse($l->isWritable());
$l->seek(1);
self::assertSame('oo', $l->getContents());
self::assertSame('foo', (string) $l);
self::assertSame(3, $l->getSize());
$this->assertInternalTypeGuzzle('array', $l->getMetadata());
$l->close();
}
public function testDetachesUnderlyingStream()
{
file_put_contents($this->fname, 'foo');
$l = new LazyOpenStream($this->fname, 'r');
$r = $l->detach();
$this->assertInternalTypeGuzzle('resource', $r);
fseek($r, 0);
self::assertSame('foo', stream_get_contents($r));
fclose($r);
}
}

View File

@ -0,0 +1,166 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\LimitStream;
use GuzzleHttp\Psr7\NoSeekStream;
use GuzzleHttp\Psr7\Stream;
/**
* @covers GuzzleHttp\Psr7\LimitStream
*/
class LimitStreamTest extends BaseTest
{
/** @var LimitStream */
private $body;
/** @var Stream */
private $decorated;
/**
* @before
*/
public function setUpTest()
{
$this->decorated = Psr7\Utils::streamFor(fopen(__FILE__, 'r'));
$this->body = new LimitStream($this->decorated, 10, 3);
}
public function testReturnsSubset()
{
$body = new LimitStream(Psr7\Utils::streamFor('foo'), -1, 1);
self::assertSame('oo', (string) $body);
self::assertTrue($body->eof());
$body->seek(0);
self::assertFalse($body->eof());
self::assertSame('oo', $body->read(100));
self::assertSame('', $body->read(1));
self::assertTrue($body->eof());
}
public function testReturnsSubsetWhenCastToString()
{
$body = Psr7\Utils::streamFor('foo_baz_bar');
$limited = new LimitStream($body, 3, 4);
self::assertSame('baz', (string) $limited);
}
public function testReturnsSubsetOfEmptyBodyWhenCastToString()
{
$body = Psr7\Utils::streamFor('01234567891234');
$limited = new LimitStream($body, 0, 10);
self::assertSame('', (string) $limited);
}
public function testReturnsSpecificSubsetOBodyWhenCastToString()
{
$body = Psr7\Utils::streamFor('0123456789abcdef');
$limited = new LimitStream($body, 3, 10);
self::assertSame('abc', (string) $limited);
}
public function testSeeksWhenConstructed()
{
self::assertSame(0, $this->body->tell());
self::assertSame(3, $this->decorated->tell());
}
public function testAllowsBoundedSeek()
{
$this->body->seek(100);
self::assertSame(10, $this->body->tell());
self::assertSame(13, $this->decorated->tell());
$this->body->seek(0);
self::assertSame(0, $this->body->tell());
self::assertSame(3, $this->decorated->tell());
try {
$this->body->seek(-10);
self::fail();
} catch (\RuntimeException $e) {
}
self::assertSame(0, $this->body->tell());
self::assertSame(3, $this->decorated->tell());
$this->body->seek(5);
self::assertSame(5, $this->body->tell());
self::assertSame(8, $this->decorated->tell());
// Fail
try {
$this->body->seek(1000, SEEK_END);
self::fail();
} catch (\RuntimeException $e) {
}
}
public function testReadsOnlySubsetOfData()
{
$data = $this->body->read(100);
self::assertSame(10, strlen($data));
self::assertSame('', $this->body->read(1000));
$this->body->setOffset(10);
$newData = $this->body->read(100);
self::assertSame(10, strlen($newData));
self::assertNotSame($data, $newData);
}
public function testThrowsWhenCurrentGreaterThanOffsetSeek()
{
$a = Psr7\Utils::streamFor('foo_bar');
$b = new NoSeekStream($a);
$c = new LimitStream($b);
$a->getContents();
$this->expectExceptionGuzzle('RuntimeException', 'Could not seek to stream offset 2');
$c->setOffset(2);
}
public function testCanGetContentsWithoutSeeking()
{
$a = Psr7\Utils::streamFor('foo_bar');
$b = new NoSeekStream($a);
$c = new LimitStream($b);
self::assertSame('foo_bar', $c->getContents());
}
public function testClaimsConsumedWhenReadLimitIsReached()
{
self::assertFalse($this->body->eof());
$this->body->read(1000);
self::assertTrue($this->body->eof());
}
public function testContentLengthIsBounded()
{
self::assertSame(10, $this->body->getSize());
}
public function testGetContentsIsBasedOnSubset()
{
$body = new LimitStream(Psr7\Utils::streamFor('foobazbar'), 3, 3);
self::assertSame('baz', $body->getContents());
}
public function testReturnsNullIfSizeCannotBeDetermined()
{
$a = new FnStream([
'getSize' => function () {
return null;
},
'tell' => function () {
return 0;
},
]);
$b = new LimitStream($a);
self::assertNull($b->getSize());
}
public function testLengthLessOffsetWhenNoLimitSize()
{
$a = Psr7\Utils::streamFor('foo_bar');
$b = new LimitStream($a, -1, 4);
self::assertSame(3, $b->getSize());
}
}

View File

@ -0,0 +1,266 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
class MessageTest extends BaseTest
{
public function testConvertsRequestsToStrings()
{
$request = new Psr7\Request('PUT', 'http://foo.com/hi?123', [
'Baz' => 'bar',
'Qux' => 'ipsum',
], 'hello', '1.0');
self::assertSame(
"PUT /hi?123 HTTP/1.0\r\nHost: foo.com\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
Psr7\Message::toString($request)
);
}
public function testConvertsResponsesToStrings()
{
$response = new Psr7\Response(200, [
'Baz' => 'bar',
'Qux' => 'ipsum',
], 'hello', '1.0', 'FOO');
self::assertSame(
"HTTP/1.0 200 FOO\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
Psr7\Message::toString($response)
);
}
public function testCorrectlyRendersSetCookieHeadersToString()
{
$response = new Psr7\Response(200, [
'Set-Cookie' => ['bar','baz','qux']
], 'hello', '1.0', 'FOO');
self::assertSame(
"HTTP/1.0 200 FOO\r\nSet-Cookie: bar\r\nSet-Cookie: baz\r\nSet-Cookie: qux\r\n\r\nhello",
Psr7\Message::toString($response)
);
}
public function testRewindsBody()
{
$body = Psr7\Utils::streamFor('abc');
$res = new Psr7\Response(200, [], $body);
Psr7\Message::rewindBody($res);
self::assertSame(0, $body->tell());
$body->rewind();
Psr7\Message::rewindBody($res);
self::assertSame(0, $body->tell());
}
public function testThrowsWhenBodyCannotBeRewound()
{
$body = Psr7\Utils::streamFor('abc');
$body->read(1);
$body = FnStream::decorate($body, [
'rewind' => function () {
throw new \RuntimeException('a');
},
]);
$res = new Psr7\Response(200, [], $body);
$this->expectExceptionGuzzle('RuntimeException');
Psr7\Message::rewindBody($res);
}
public function testParsesRequestMessages()
{
$req = "GET /abc HTTP/1.0\r\nHost: foo.com\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest";
$request = Psr7\Message::parseRequest($req);
self::assertSame('GET', $request->getMethod());
self::assertSame('/abc', $request->getRequestTarget());
self::assertSame('1.0', $request->getProtocolVersion());
self::assertSame('foo.com', $request->getHeaderLine('Host'));
self::assertSame('Bar', $request->getHeaderLine('Foo'));
self::assertSame('Bam, Qux', $request->getHeaderLine('Baz'));
self::assertSame('Test', (string)$request->getBody());
self::assertSame('http://foo.com/abc', (string)$request->getUri());
}
public function testParsesRequestMessagesWithHttpsScheme()
{
$req = "PUT /abc?baz=bar HTTP/1.1\r\nHost: foo.com:443\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('PUT', $request->getMethod());
self::assertSame('/abc?baz=bar', $request->getRequestTarget());
self::assertSame('1.1', $request->getProtocolVersion());
self::assertSame('foo.com:443', $request->getHeaderLine('Host'));
self::assertSame('', (string)$request->getBody());
self::assertSame('https://foo.com/abc?baz=bar', (string)$request->getUri());
}
public function testParsesRequestMessagesWithUriWhenHostIsNotFirst()
{
$req = "PUT / HTTP/1.1\r\nFoo: Bar\r\nHost: foo.com\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('PUT', $request->getMethod());
self::assertSame('/', $request->getRequestTarget());
self::assertSame('http://foo.com/', (string)$request->getUri());
}
public function testParsesRequestMessagesWithFullUri()
{
$req = "GET https://www.google.com:443/search?q=foobar HTTP/1.1\r\nHost: www.google.com\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('GET', $request->getMethod());
self::assertSame('https://www.google.com:443/search?q=foobar', $request->getRequestTarget());
self::assertSame('1.1', $request->getProtocolVersion());
self::assertSame('www.google.com', $request->getHeaderLine('Host'));
self::assertSame('', (string)$request->getBody());
self::assertSame('https://www.google.com/search?q=foobar', (string)$request->getUri());
}
public function testParsesRequestMessagesWithCustomMethod()
{
$req = "GET_DATA / HTTP/1.1\r\nFoo: Bar\r\nHost: foo.com\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('GET_DATA', $request->getMethod());
}
public function testParsesRequestMessagesWithFoldedHeadersOnHttp10()
{
$req = "PUT / HTTP/1.0\r\nFoo: Bar\r\n Bam\r\n\r\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('PUT', $request->getMethod());
self::assertSame('/', $request->getRequestTarget());
self::assertSame('Bar Bam', $request->getHeaderLine('Foo'));
}
public function testRequestParsingFailsWithFoldedHeadersOnHttp11()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid header syntax: Obsolete line folding');
Psr7\Message::parseResponse("GET_DATA / HTTP/1.1\r\nFoo: Bar\r\n Biz: Bam\r\n\r\n");
}
public function testParsesRequestMessagesWhenHeaderDelimiterIsOnlyALineFeed()
{
$req = "PUT / HTTP/1.0\nFoo: Bar\nBaz: Bam\n\n";
$request = Psr7\Message::parseRequest($req);
self::assertSame('PUT', $request->getMethod());
self::assertSame('/', $request->getRequestTarget());
self::assertSame('Bar', $request->getHeaderLine('Foo'));
self::assertSame('Bam', $request->getHeaderLine('Baz'));
}
public function testValidatesRequestMessages()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
Psr7\Message::parseRequest("HTTP/1.1 200 OK\r\n\r\n");
}
public function testParsesResponseMessages()
{
$res = "HTTP/1.0 200 OK\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('Bam, Qux', $response->getHeaderLine('Baz'));
self::assertSame('Test', (string)$response->getBody());
}
public function testParsesResponseWithoutReason()
{
$res = "HTTP/1.0 200\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('Bam, Qux', $response->getHeaderLine('Baz'));
self::assertSame('Test', (string)$response->getBody());
}
public function testParsesResponseWithLeadingDelimiter()
{
$res = "\r\nHTTP/1.0 200\r\nFoo: Bar\r\n\r\nTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('Test', (string)$response->getBody());
}
public function testParsesResponseWithFoldedHeadersOnHttp10()
{
$res = "HTTP/1.0 200\r\nFoo: Bar\r\n Bam\r\n\r\nTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar Bam', $response->getHeaderLine('Foo'));
self::assertSame('Test', (string)$response->getBody());
}
public function testResponseParsingFailsWithFoldedHeadersOnHttp11()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid header syntax: Obsolete line folding');
Psr7\Message::parseResponse("HTTP/1.1 200\r\nFoo: Bar\r\n Biz: Bam\r\nBaz: Qux\r\n\r\nTest");
}
public function testParsesResponseWhenHeaderDelimiterIsOnlyALineFeed()
{
$res = "HTTP/1.0 200\nFoo: Bar\nBaz: Bam\n\nTest\n\nOtherTest";
$response = Psr7\Message::parseResponse($res);
self::assertSame(200, $response->getStatusCode());
self::assertSame('OK', $response->getReasonPhrase());
self::assertSame('1.0', $response->getProtocolVersion());
self::assertSame('Bar', $response->getHeaderLine('Foo'));
self::assertSame('Bam', $response->getHeaderLine('Baz'));
self::assertSame("Test\n\nOtherTest", (string)$response->getBody());
}
public function testResponseParsingFailsWithoutHeaderDelimiter()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid message: Missing header delimiter');
Psr7\Message::parseResponse("HTTP/1.0 200\r\nFoo: Bar\r\n Baz: Bam\r\nBaz: Qux\r\n");
}
public function testValidatesResponseMessages()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
Psr7\Message::parseResponse("GET / HTTP/1.1\r\n\r\n");
}
public function testMessageBodySummaryWithSmallBody()
{
$message = new Psr7\Response(200, [], 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
self::assertSame('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', Psr7\Message::bodySummary($message));
}
public function testMessageBodySummaryWithLargeBody()
{
$message = new Psr7\Response(200, [], 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.');
self::assertSame('Lorem ipsu (truncated...)', Psr7\Message::bodySummary($message, 10));
}
public function testMessageBodySummaryWithSpecialUTF8Characters()
{
$message = new Psr7\Response(200, [], '’é€௵ဪ‱');
self::assertSame('’é€௵ဪ‱', Psr7\Message::bodySummary($message));
}
public function testMessageBodySummaryWithEmptyBody()
{
$message = new Psr7\Response(200, [], '');
self::assertNull(Psr7\Message::bodySummary($message));
}
public function testGetResponseBodySummaryOfNonReadableStream()
{
self::assertNull(Psr7\Message::bodySummary(new Psr7\Response(500, [], new ReadSeekOnlyStream())));
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
class MimeTypeTest extends BaseTest
{
public function testDetermineFromExtension()
{
self::assertNull(Psr7\MimeType::fromExtension('not-a-real-extension'));
self::assertSame('application/json', Psr7\MimeType::fromExtension('json'));
}
public function testDetermineFromFilename()
{
self::assertSame(
'image/jpeg',
Psr7\MimeType::fromFilename('/tmp/images/IMG034821.JPEG')
);
}
}

View File

@ -0,0 +1,245 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\MultipartStream;
class MultipartStreamTest extends BaseTest
{
public function testCreatesDefaultBoundary()
{
$b = new MultipartStream();
self::assertNotEmpty($b->getBoundary());
}
public function testCanProvideBoundary()
{
$b = new MultipartStream([], 'foo');
self::assertSame('foo', $b->getBoundary());
}
public function testIsNotWritable()
{
$b = new MultipartStream();
self::assertFalse($b->isWritable());
}
public function testCanCreateEmptyStream()
{
$b = new MultipartStream();
$boundary = $b->getBoundary();
self::assertSame("--{$boundary}--\r\n", $b->getContents());
self::assertSame(strlen($boundary) + 6, $b->getSize());
}
public function testValidatesFilesArrayElement()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new MultipartStream([['foo' => 'bar']]);
}
public function testEnsuresFileHasName()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new MultipartStream([['contents' => 'bar']]);
}
public function testSerializesFields()
{
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => 'bar'
],
[
'name' => 'baz',
'contents' => 'bam'
]
], 'boundary');
self::assertSame(
"--boundary\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Length: 3\r\n\r\n"
. "bar\r\n--boundary\r\nContent-Disposition: form-data; name=\"baz\"\r\nContent-Length: 3"
. "\r\n\r\nbam\r\n--boundary--\r\n",
(string) $b
);
}
public function testSerializesNonStringFields()
{
$b = new MultipartStream([
[
'name' => 'int',
'contents' => (int) 1
],
[
'name' => 'bool',
'contents' => (boolean) false
],
[
'name' => 'bool2',
'contents' => (boolean) true
],
[
'name' => 'float',
'contents' => (float) 1.1
]
], 'boundary');
self::assertSame(
"--boundary\r\nContent-Disposition: form-data; name=\"int\"\r\nContent-Length: 1\r\n\r\n"
. "1\r\n--boundary\r\nContent-Disposition: form-data; name=\"bool\"\r\n\r\n\r\n--boundary"
. "\r\nContent-Disposition: form-data; name=\"bool2\"\r\nContent-Length: 1\r\n\r\n"
. "1\r\n--boundary\r\nContent-Disposition: form-data; name=\"float\"\r\nContent-Length: 3"
. "\r\n\r\n1.1\r\n--boundary--\r\n",
(string) $b
);
}
public function testSerializesFiles()
{
$f1 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [
'getMetadata' => function () {
return '/foo/bar.txt';
}
]);
$f2 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('baz'), [
'getMetadata' => function () {
return '/foo/baz.jpg';
}
]);
$f3 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('bar'), [
'getMetadata' => function () {
return '/foo/bar.gif';
}
]);
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => $f1
],
[
'name' => 'qux',
'contents' => $f2
],
[
'name' => 'qux',
'contents' => $f3
],
], 'boundary');
$expected = <<<EOT
--boundary
Content-Disposition: form-data; name="foo"; filename="bar.txt"
Content-Length: 3
Content-Type: text/plain
foo
--boundary
Content-Disposition: form-data; name="qux"; filename="baz.jpg"
Content-Length: 3
Content-Type: image/jpeg
baz
--boundary
Content-Disposition: form-data; name="qux"; filename="bar.gif"
Content-Length: 3
Content-Type: image/gif
bar
--boundary--
EOT;
self::assertSame($expected, str_replace("\r", '', $b));
}
public function testSerializesFilesWithCustomHeaders()
{
$f1 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [
'getMetadata' => function () {
return '/foo/bar.txt';
}
]);
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => $f1,
'headers' => [
'x-foo' => 'bar',
'content-disposition' => 'custom'
]
]
], 'boundary');
$expected = <<<EOT
--boundary
x-foo: bar
content-disposition: custom
Content-Length: 3
Content-Type: text/plain
foo
--boundary--
EOT;
self::assertSame($expected, str_replace("\r", '', $b));
}
public function testSerializesFilesWithCustomHeadersAndMultipleValues()
{
$f1 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [
'getMetadata' => function () {
return '/foo/bar.txt';
}
]);
$f2 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('baz'), [
'getMetadata' => function () {
return '/foo/baz.jpg';
}
]);
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => $f1,
'headers' => [
'x-foo' => 'bar',
'content-disposition' => 'custom'
]
],
[
'name' => 'foo',
'contents' => $f2,
'headers' => ['cOntenT-Type' => 'custom'],
]
], 'boundary');
$expected = <<<EOT
--boundary
x-foo: bar
content-disposition: custom
Content-Length: 3
Content-Type: text/plain
foo
--boundary
cOntenT-Type: custom
Content-Disposition: form-data; name="foo"; filename="baz.jpg"
Content-Length: 3
baz
--boundary--
EOT;
self::assertSame($expected, str_replace("\r", '', $b));
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\NoSeekStream;
/**
* @covers GuzzleHttp\Psr7\NoSeekStream
* @covers GuzzleHttp\Psr7\StreamDecoratorTrait
*/
class NoSeekStreamTest extends BaseTest
{
public function testCannotSeek()
{
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isSeekable', 'seek'])
->getMockForAbstractClass();
$s->expects(self::never())->method('seek');
$s->expects(self::never())->method('isSeekable');
$wrapped = new NoSeekStream($s);
self::assertFalse($wrapped->isSeekable());
$this->expectExceptionGuzzle('RuntimeException', 'Cannot seek a NoSeekStream');
$wrapped->seek(2);
}
public function testToStringDoesNotSeek()
{
$s = \GuzzleHttp\Psr7\Utils::streamFor('foo');
$s->seek(1);
$wrapped = new NoSeekStream($s);
self::assertSame('oo', (string) $wrapped);
$wrapped->close();
}
}

View File

@ -0,0 +1,78 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\LimitStream;
use GuzzleHttp\Psr7\PumpStream;
class PumpStreamTest extends BaseTest
{
public function testHasMetadataAndSize()
{
$p = new PumpStream(function () {
}, [
'metadata' => ['foo' => 'bar'],
'size' => 100
]);
self::assertSame('bar', $p->getMetadata('foo'));
self::assertSame(['foo' => 'bar'], $p->getMetadata());
self::assertSame(100, $p->getSize());
}
public function testCanReadFromCallable()
{
$p = Psr7\Utils::streamFor(function ($size) {
return 'a';
});
self::assertSame('a', $p->read(1));
self::assertSame(1, $p->tell());
self::assertSame('aaaaa', $p->read(5));
self::assertSame(6, $p->tell());
}
public function testStoresExcessDataInBuffer()
{
$called = [];
$p = Psr7\Utils::streamFor(function ($size) use (&$called) {
$called[] = $size;
return 'abcdef';
});
self::assertSame('a', $p->read(1));
self::assertSame('b', $p->read(1));
self::assertSame('cdef', $p->read(4));
self::assertSame('abcdefabc', $p->read(9));
self::assertSame([1, 9, 3], $called);
}
public function testInifiniteStreamWrappedInLimitStream()
{
$p = Psr7\Utils::streamFor(function () {
return 'a';
});
$s = new LimitStream($p, 5);
self::assertSame('aaaaa', (string) $s);
}
public function testDescribesCapabilities()
{
$p = Psr7\Utils::streamFor(function () {
});
self::assertTrue($p->isReadable());
self::assertFalse($p->isSeekable());
self::assertFalse($p->isWritable());
self::assertNull($p->getSize());
self::assertSame('', $p->getContents());
self::assertSame('', (string) $p);
$p->close();
self::assertSame('', $p->read(10));
self::assertTrue($p->eof());
try {
self::assertFalse($p->write('aa'));
self::fail();
} catch (\RuntimeException $e) {
}
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
class QueryTest extends BaseTest
{
public function parseQueryProvider()
{
return [
// Does not need to parse when the string is empty
['', []],
// Can parse mult-values items
['q=a&q=b', ['q' => ['a', 'b']]],
// Can parse multi-valued items that use numeric indices
['q[0]=a&q[1]=b', ['q[0]' => 'a', 'q[1]' => 'b']],
// Can parse duplicates and does not include numeric indices
['q[]=a&q[]=b', ['q[]' => ['a', 'b']]],
// Ensures that the value of "q" is an array even though one value
['q[]=a', ['q[]' => 'a']],
// Does not modify "." to "_" like PHP's parse_str()
['q.a=a&q.b=b', ['q.a' => 'a', 'q.b' => 'b']],
// Can decode %20 to " "
['q%20a=a%20b', ['q a' => 'a b']],
// Can parse funky strings with no values by assigning each to null
['q&a', ['q' => null, 'a' => null]],
// Does not strip trailing equal signs
['data=abc=', ['data' => 'abc=']],
// Can store duplicates without affecting other values
['foo=a&foo=b&?µ=c', ['foo' => ['a', 'b'], '?µ' => 'c']],
// Sets value to null when no "=" is present
['foo', ['foo' => null]],
// Preserves "0" keys.
['0', ['0' => null]],
// Sets the value to an empty string when "=" is present
['0=', ['0' => '']],
// Preserves falsey keys
['var=0', ['var' => '0']],
['a[b][c]=1&a[b][c]=2', ['a[b][c]' => ['1', '2']]],
['a[b]=c&a[d]=e', ['a[b]' => 'c', 'a[d]' => 'e']],
// Ensure it doesn't leave things behind with repeated values
// Can parse mult-values items
['q=a&q=b&q=c', ['q' => ['a', 'b', 'c']]],
];
}
/**
* @dataProvider parseQueryProvider
*/
public function testParsesQueries($input, $output)
{
$result = Psr7\Query::parse($input);
self::assertSame($output, $result);
}
public function testDoesNotDecode()
{
$str = 'foo%20=bar';
$data = Psr7\Query::parse($str, false);
self::assertSame(['foo%20' => 'bar'], $data);
}
/**
* @dataProvider parseQueryProvider
*/
public function testParsesAndBuildsQueries($input)
{
$result = Psr7\Query::parse($input, false);
self::assertSame($input, Psr7\Query::build($result, false));
}
public function testEncodesWithRfc1738()
{
$str = Psr7\Query::build(['foo bar' => 'baz+'], PHP_QUERY_RFC1738);
self::assertSame('foo+bar=baz%2B', $str);
}
public function testEncodesWithRfc3986()
{
$str = Psr7\Query::build(['foo bar' => 'baz+'], PHP_QUERY_RFC3986);
self::assertSame('foo%20bar=baz%2B', $str);
}
public function testDoesNotEncode()
{
$str = Psr7\Query::build(['foo bar' => 'baz+'], false);
self::assertSame('foo bar=baz+', $str);
}
public function testCanControlDecodingType()
{
$result = Psr7\Query::parse('var=foo+bar', PHP_QUERY_RFC3986);
self::assertSame('foo+bar', $result['var']);
$result = Psr7\Query::parse('var=foo+bar', PHP_QUERY_RFC1738);
self::assertSame('foo bar', $result['var']);
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Stream;
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,298 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
/**
* @covers GuzzleHttp\Psr7\MessageTrait
* @covers GuzzleHttp\Psr7\Request
*/
class RequestTest extends BaseTest
{
public function testRequestUriMayBeString()
{
$r = new Request('GET', '/');
self::assertSame('/', (string) $r->getUri());
}
public function testRequestUriMayBeUri()
{
$uri = new Uri('/');
$r = new Request('GET', $uri);
self::assertSame($uri, $r->getUri());
}
public function testValidateRequestUri()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new Request('GET', '///');
}
public function testCanConstructWithBody()
{
$r = new Request('GET', '/', [], 'baz');
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('baz', (string) $r->getBody());
}
public function testNullBody()
{
$r = new Request('GET', '/', [], null);
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('', (string) $r->getBody());
}
public function testFalseyBody()
{
$r = new Request('GET', '/', [], '0');
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('0', (string) $r->getBody());
}
public function testConstructorDoesNotReadStreamBody()
{
$streamIsRead = false;
$body = Psr7\FnStream::decorate(Psr7\Utils::streamFor(''), [
'__toString' => function () use (&$streamIsRead) {
$streamIsRead = true;
return '';
}
]);
$r = new Request('GET', '/', [], $body);
self::assertFalse($streamIsRead);
self::assertSame($body, $r->getBody());
}
public function testCapitalizesMethod()
{
$r = new Request('get', '/');
self::assertSame('GET', $r->getMethod());
}
public function testCapitalizesWithMethod()
{
$r = new Request('GET', '/');
self::assertSame('PUT', $r->withMethod('put')->getMethod());
}
public function testWithUri()
{
$r1 = new Request('GET', '/');
$u1 = $r1->getUri();
$u2 = new Uri('http://www.example.com');
$r2 = $r1->withUri($u2);
self::assertNotSame($r1, $r2);
self::assertSame($u2, $r2->getUri());
self::assertSame($u1, $r1->getUri());
}
/**
* @dataProvider invalidMethodsProvider
*/
public function testConstructWithInvalidMethods($method)
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new Request($method, '/');
}
/**
* @dataProvider invalidMethodsProvider
*/
public function testWithInvalidMethods($method)
{
$r = new Request('get', '/');
$this->expectExceptionGuzzle('InvalidArgumentException');
$r->withMethod($method);
}
public function invalidMethodsProvider()
{
return [
[null],
[false],
[['foo']],
[new \stdClass()],
];
}
public function testSameInstanceWhenSameUri()
{
$r1 = new Request('GET', 'http://foo.com');
$r2 = $r1->withUri($r1->getUri());
self::assertSame($r1, $r2);
}
public function testWithRequestTarget()
{
$r1 = new Request('GET', '/');
$r2 = $r1->withRequestTarget('*');
self::assertSame('*', $r2->getRequestTarget());
self::assertSame('/', $r1->getRequestTarget());
}
public function testRequestTargetDoesNotAllowSpaces()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
$r1 = new Request('GET', '/');
$r1->withRequestTarget('/foo bar');
}
public function testRequestTargetDefaultsToSlash()
{
$r1 = new Request('GET', '');
self::assertSame('/', $r1->getRequestTarget());
$r2 = new Request('GET', '*');
self::assertSame('*', $r2->getRequestTarget());
$r3 = new Request('GET', 'http://foo.com/bar baz/');
self::assertSame('/bar%20baz/', $r3->getRequestTarget());
}
public function testBuildsRequestTarget()
{
$r1 = new Request('GET', 'http://foo.com/baz?bar=bam');
self::assertSame('/baz?bar=bam', $r1->getRequestTarget());
}
public function testBuildsRequestTargetWithFalseyQuery()
{
$r1 = new Request('GET', 'http://foo.com/baz?0');
self::assertSame('/baz?0', $r1->getRequestTarget());
}
public function testHostIsAddedFirst()
{
$r = new Request('GET', 'http://foo.com/baz?bar=bam', ['Foo' => 'Bar']);
self::assertSame([
'Host' => ['foo.com'],
'Foo' => ['Bar']
], $r->getHeaders());
}
public function testHeaderValueWithWhitespace()
{
$r = new Request('GET', 'https://example.com/', [
'User-Agent' => 'Linux f0f489981e90 5.10.104-linuxkit 1 SMP Wed Mar 9 19:05:23 UTC 2022 x86_64'
]);
self::assertSame([
'Host' => ['example.com'],
'User-Agent' => ['Linux f0f489981e90 5.10.104-linuxkit 1 SMP Wed Mar 9 19:05:23 UTC 2022 x86_64']
], $r->getHeaders());
}
public function testCanGetHeaderAsCsv()
{
$r = new Request('GET', 'http://foo.com/baz?bar=bam', [
'Foo' => ['a', 'b', 'c']
]);
self::assertSame('a, b, c', $r->getHeaderLine('Foo'));
self::assertSame('', $r->getHeaderLine('Bar'));
}
public function testHostIsNotOverwrittenWhenPreservingHost()
{
$r = new Request('GET', 'http://foo.com/baz?bar=bam', ['Host' => 'a.com']);
self::assertSame(['Host' => ['a.com']], $r->getHeaders());
$r2 = $r->withUri(new Uri('http://www.foo.com/bar'), true);
self::assertSame('a.com', $r2->getHeaderLine('Host'));
}
public function testWithUriSetsHostIfNotSet()
{
$r = (new Request('GET', 'http://foo.com/baz?bar=bam'))->withoutHeader('Host');
self::assertSame([], $r->getHeaders());
$r2 = $r->withUri(new Uri('http://www.baz.com/bar'), true);
self::assertSame('www.baz.com', $r2->getHeaderLine('Host'));
}
public function testOverridesHostWithUri()
{
$r = new Request('GET', 'http://foo.com/baz?bar=bam');
self::assertSame(['Host' => ['foo.com']], $r->getHeaders());
$r2 = $r->withUri(new Uri('http://www.baz.com/bar'));
self::assertSame('www.baz.com', $r2->getHeaderLine('Host'));
}
public function testAggregatesHeaders()
{
$r = new Request('GET', '', [
'ZOO' => 'zoobar',
'zoo' => ['foobar', 'zoobar']
]);
self::assertSame(['ZOO' => ['zoobar', 'foobar', 'zoobar']], $r->getHeaders());
self::assertSame('zoobar, foobar, zoobar', $r->getHeaderLine('zoo'));
}
public function testAddsPortToHeader()
{
$r = new Request('GET', 'http://foo.com:8124/bar');
self::assertSame('foo.com:8124', $r->getHeaderLine('host'));
}
public function testAddsPortToHeaderAndReplacePreviousPort()
{
$r = new Request('GET', 'http://foo.com:8124/bar');
$r = $r->withUri(new Uri('http://foo.com:8125/bar'));
self::assertSame('foo.com:8125', $r->getHeaderLine('host'));
}
/**
* @dataProvider provideHeaderValuesContainingNotAllowedChars
*/
public function testContainsNotAllowedCharsOnHeaderValue($value)
{
$this->expectExceptionGuzzle('InvalidArgumentException', sprintf('"%s" is not valid header value', $value));
$r = new Request(
'GET',
'http://foo.com/baz?bar=bam',
[
'testing' => $value
]
);
}
/**
* @return iterable
*/
public function provideHeaderValuesContainingNotAllowedChars()
{
// Explicit tests for newlines as the most common exploit vector.
$tests = [
["new\nline"],
["new\r\nline"],
["new\rline"],
// Line folding is technically allowed, but deprecated.
// We don't support it.
["new\r\n line"],
["newline\n"],
["\nnewline"],
["newline\r\n"],
["\r\nnewline"],
];
for ($i = 0; $i <= 0xff; $i++) {
if (\chr($i) == "\t") {
continue;
}
if (\chr($i) == " ") {
continue;
}
if ($i >= 0x21 && $i <= 0x7e) {
continue;
}
if ($i >= 0x80) {
continue;
}
$tests[] = ["foo" . \chr($i) . "bar"];
$tests[] = ["foo" . \chr($i)];
}
return $tests;
}
}

View File

@ -0,0 +1,384 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Response;
/**
* @covers GuzzleHttp\Psr7\MessageTrait
* @covers GuzzleHttp\Psr7\Response
*/
class ResponseTest extends BaseTest
{
public function testDefaultConstructor()
{
$r = new Response();
self::assertSame(200, $r->getStatusCode());
self::assertSame('1.1', $r->getProtocolVersion());
self::assertSame('OK', $r->getReasonPhrase());
self::assertSame([], $r->getHeaders());
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('', (string) $r->getBody());
}
public function testCanConstructWithStatusCode()
{
$r = new Response(404);
self::assertSame(404, $r->getStatusCode());
self::assertSame('Not Found', $r->getReasonPhrase());
}
public function testConstructorDoesNotReadStreamBody()
{
$streamIsRead = false;
$body = Psr7\FnStream::decorate(Psr7\Utils::streamFor(''), [
'__toString' => function () use (&$streamIsRead) {
$streamIsRead = true;
return '';
}
]);
$r = new Response(200, [], $body);
self::assertFalse($streamIsRead);
self::assertSame($body, $r->getBody());
}
public function testStatusCanBeNumericString()
{
$r = new Response('404');
$r2 = $r->withStatus('201');
self::assertSame(404, $r->getStatusCode());
self::assertSame('Not Found', $r->getReasonPhrase());
self::assertSame(201, $r2->getStatusCode());
self::assertSame('Created', $r2->getReasonPhrase());
}
public function testCanConstructWithHeaders()
{
$r = new Response(200, ['Foo' => 'Bar']);
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame('Bar', $r->getHeaderLine('Foo'));
self::assertSame(['Bar'], $r->getHeader('Foo'));
}
public function testCanConstructWithHeadersAsArray()
{
$r = new Response(200, [
'Foo' => ['baz', 'bar']
]);
self::assertSame(['Foo' => ['baz', 'bar']], $r->getHeaders());
self::assertSame('baz, bar', $r->getHeaderLine('Foo'));
self::assertSame(['baz', 'bar'], $r->getHeader('Foo'));
}
public function testCanConstructWithBody()
{
$r = new Response(200, [], 'baz');
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('baz', (string) $r->getBody());
}
public function testNullBody()
{
$r = new Response(200, [], null);
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('', (string) $r->getBody());
}
public function testFalseyBody()
{
$r = new Response(200, [], '0');
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('0', (string) $r->getBody());
}
public function testCanConstructWithReason()
{
$r = new Response(200, [], null, '1.1', 'bar');
self::assertSame('bar', $r->getReasonPhrase());
$r = new Response(200, [], null, '1.1', '0');
self::assertSame('0', $r->getReasonPhrase(), 'Falsey reason works');
}
public function testCanConstructWithProtocolVersion()
{
$r = new Response(200, [], null, '1000');
self::assertSame('1000', $r->getProtocolVersion());
}
public function testWithStatusCodeAndNoReason()
{
$r = (new Response())->withStatus(201);
self::assertSame(201, $r->getStatusCode());
self::assertSame('Created', $r->getReasonPhrase());
}
public function testWithStatusCodeAndReason()
{
$r = (new Response())->withStatus(201, 'Foo');
self::assertSame(201, $r->getStatusCode());
self::assertSame('Foo', $r->getReasonPhrase());
$r = (new Response())->withStatus(201, '0');
self::assertSame(201, $r->getStatusCode());
self::assertSame('0', $r->getReasonPhrase(), 'Falsey reason works');
}
public function testWithProtocolVersion()
{
$r = (new Response())->withProtocolVersion('1000');
self::assertSame('1000', $r->getProtocolVersion());
}
public function testSameInstanceWhenSameProtocol()
{
$r = new Response();
self::assertSame($r, $r->withProtocolVersion('1.1'));
}
public function testWithBody()
{
$b = Psr7\Utils::streamFor('0');
$r = (new Response())->withBody($b);
self::assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody());
self::assertSame('0', (string) $r->getBody());
}
public function testSameInstanceWhenSameBody()
{
$r = new Response();
$b = $r->getBody();
self::assertSame($r, $r->withBody($b));
}
public function testWithHeader()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withHeader('baZ', 'Bam');
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar'], 'baZ' => ['Bam']], $r2->getHeaders());
self::assertSame('Bam', $r2->getHeaderLine('baz'));
self::assertSame(['Bam'], $r2->getHeader('baz'));
}
public function testNumericHeaderValue()
{
$r = (new Response())->withHeader('Api-Version', 1);
self::assertSame(['Api-Version' => ['1']], $r->getHeaders());
}
public function testWithHeaderAsArray()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withHeader('baZ', ['Bam', 'Bar']);
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar'], 'baZ' => ['Bam', 'Bar']], $r2->getHeaders());
self::assertSame('Bam, Bar', $r2->getHeaderLine('baz'));
self::assertSame(['Bam', 'Bar'], $r2->getHeader('baz'));
}
public function testWithHeaderReplacesDifferentCase()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withHeader('foO', 'Bam');
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['foO' => ['Bam']], $r2->getHeaders());
self::assertSame('Bam', $r2->getHeaderLine('foo'));
self::assertSame(['Bam'], $r2->getHeader('foo'));
}
public function testWithAddedHeader()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withAddedHeader('foO', 'Baz');
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar', 'Baz']], $r2->getHeaders());
self::assertSame('Bar, Baz', $r2->getHeaderLine('foo'));
self::assertSame(['Bar', 'Baz'], $r2->getHeader('foo'));
}
public function testWithAddedHeaderAsArray()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withAddedHeader('foO', ['Baz', 'Bam']);
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar', 'Baz', 'Bam']], $r2->getHeaders());
self::assertSame('Bar, Baz, Bam', $r2->getHeaderLine('foo'));
self::assertSame(['Bar', 'Baz', 'Bam'], $r2->getHeader('foo'));
}
public function testWithAddedHeaderThatDoesNotExist()
{
$r = new Response(200, ['Foo' => 'Bar']);
$r2 = $r->withAddedHeader('nEw', 'Baz');
self::assertSame(['Foo' => ['Bar']], $r->getHeaders());
self::assertSame(['Foo' => ['Bar'], 'nEw' => ['Baz']], $r2->getHeaders());
self::assertSame('Baz', $r2->getHeaderLine('new'));
self::assertSame(['Baz'], $r2->getHeader('new'));
}
public function testWithoutHeaderThatExists()
{
$r = new Response(200, ['Foo' => 'Bar', 'Baz' => 'Bam']);
$r2 = $r->withoutHeader('foO');
self::assertTrue($r->hasHeader('foo'));
self::assertSame(['Foo' => ['Bar'], 'Baz' => ['Bam']], $r->getHeaders());
self::assertFalse($r2->hasHeader('foo'));
self::assertSame(['Baz' => ['Bam']], $r2->getHeaders());
}
public function testWithoutHeaderThatDoesNotExist()
{
$r = new Response(200, ['Baz' => 'Bam']);
$r2 = $r->withoutHeader('foO');
self::assertSame($r, $r2);
self::assertFalse($r2->hasHeader('foo'));
self::assertSame(['Baz' => ['Bam']], $r2->getHeaders());
}
public function testSameInstanceWhenRemovingMissingHeader()
{
$r = new Response();
self::assertSame($r, $r->withoutHeader('foo'));
}
public function testPassNumericHeaderNameInConstructor()
{
$r = new Response(200, ['Location' => 'foo', '123' => 'bar']);
self::assertSame('bar', $r->getHeaderLine('123'));
}
/**
* @dataProvider invalidHeaderProvider
*/
public function testConstructResponseInvalidHeader($header, $headerValue, $expectedMessage)
{
$this->expectExceptionGuzzle('InvalidArgumentException', $expectedMessage);
new Response(200, [$header => $headerValue]);
}
public function invalidHeaderProvider()
{
return [
['foo', [], 'Header value can not be an empty array.'],
['', '', 'Header name can not be empty.'],
['foo', new \stdClass(), 'Header value must be scalar or null but stdClass provided.'],
];
}
/**
* @dataProvider invalidWithHeaderProvider
*/
public function testWithInvalidHeader($header, $headerValue, $expectedMessage)
{
$r = new Response();
$this->expectExceptionGuzzle('InvalidArgumentException', $expectedMessage);
$r->withHeader($header, $headerValue);
}
public function invalidWithHeaderProvider()
{
return array_merge($this->invalidHeaderProvider(), [
[[], 'foo', 'Header name must be a string but array provided.'],
[false, 'foo', 'Header name must be a string but boolean provided.'],
[new \stdClass(), 'foo', 'Header name must be a string but stdClass provided.'],
["", 'foo', "Header name can not be empty."],
["Content-Type\r\n\r\n", 'foo', "\"Content-Type\r\n\r\n\" is not valid header name."],
["Content-Type\r\n", 'foo', "\"Content-Type\r\n\" is not valid header name."],
["Content-Type\n", 'foo', "\"Content-Type\n\" is not valid header name."],
["\r\nContent-Type", 'foo', "\"\r\nContent-Type\" is not valid header name."],
["\nContent-Type", 'foo', "\"\nContent-Type\" is not valid header name."],
["\n", 'foo', "\"\n\" is not valid header name."],
["\r\n", 'foo', "\"\r\n\" is not valid header name."],
["\t", 'foo', "\"\t\" is not valid header name."],
]);
}
public function testHeaderValuesAreTrimmed()
{
$r1 = new Response(200, ['OWS' => " \t \tFoo\t \t "]);
$r2 = (new Response())->withHeader('OWS', " \t \tFoo\t \t ");
$r3 = (new Response())->withAddedHeader('OWS', " \t \tFoo\t \t ");
foreach ([$r1, $r2, $r3] as $r) {
self::assertSame(['OWS' => ['Foo']], $r->getHeaders());
self::assertSame('Foo', $r->getHeaderLine('OWS'));
self::assertSame(['Foo'], $r->getHeader('OWS'));
}
}
public function testWithAddedHeaderArrayValueAndKeys()
{
$message = (new Response())->withAddedHeader('list', ['foo' => 'one']);
$message = $message->withAddedHeader('list', ['foo' => 'two', 'bar' => 'three']);
$headerLine = $message->getHeaderLine('list');
self::assertSame('one, two, three', $headerLine);
}
/**
* @dataProvider nonIntegerStatusCodeProvider
*
* @param mixed $invalidValues
*/
public function testConstructResponseWithNonIntegerStatusCode($invalidValues)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Status code must be an integer value.');
new Response($invalidValues);
}
/**
* @dataProvider nonIntegerStatusCodeProvider
*
* @param mixed $invalidValues
*/
public function testResponseChangeStatusCodeWithNonInteger($invalidValues)
{
$response = new Response();
$this->expectExceptionGuzzle('InvalidArgumentException', 'Status code must be an integer value.');
$response->withStatus($invalidValues);
}
public function nonIntegerStatusCodeProvider()
{
return [
['whatever'],
['1.01'],
[1.01],
[new \stdClass()],
];
}
/**
* @dataProvider invalidStatusCodeRangeProvider
*
* @param mixed $invalidValues
*/
public function testConstructResponseWithInvalidRangeStatusCode($invalidValues)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Status code must be an integer value between 1xx and 5xx.');
new Response($invalidValues);
}
/**
* @dataProvider invalidStatusCodeRangeProvider
*
* @param mixed $invalidValues
*/
public function testResponseChangeStatusCodeWithWithInvalidRange($invalidValues)
{
$response = new Response();
$this->expectExceptionGuzzle('InvalidArgumentException', 'Status code must be an integer value between 1xx and 5xx.');
$response->withStatus($invalidValues);
}
public function invalidStatusCodeRangeProvider()
{
return [
[600],
[99],
];
}
}

View File

@ -0,0 +1,544 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\ServerRequest;
use GuzzleHttp\Psr7\UploadedFile;
use GuzzleHttp\Psr7\Uri;
/**
* @covers GuzzleHttp\Psr7\ServerRequest
*/
class ServerRequestTest extends BaseTest
{
public function dataNormalizeFiles()
{
return [
'Single file' => [
[
'file' => [
'name' => 'MyFile.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/php/php1h4j1o',
'error' => '0',
'size' => '123'
]
],
[
'file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
)
]
],
'Empty file' => [
[
'image_file' => [
'name' => '',
'type' => '',
'tmp_name' => '',
'error' => '4',
'size' => '0'
]
],
[
'image_file' => new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
)
]
],
'Already Converted' => [
[
'file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
)
],
[
'file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
)
]
],
'Already Converted array' => [
[
'file' => [
new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
)
],
],
[
'file' => [
new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
)
],
]
],
'Multiple files' => [
[
'text_file' => [
'name' => 'MyFile.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/php/php1h4j1o',
'error' => '0',
'size' => '123'
],
'image_file' => [
'name' => '',
'type' => '',
'tmp_name' => '',
'error' => '4',
'size' => '0'
]
],
[
'text_file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
'image_file' => new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
)
]
],
'Nested files' => [
[
'file' => [
'name' => [
0 => 'MyFile.txt',
1 => 'Image.png',
],
'type' => [
0 => 'text/plain',
1 => 'image/png',
],
'tmp_name' => [
0 => '/tmp/php/hp9hskjhf',
1 => '/tmp/php/php1h4j1o',
],
'error' => [
0 => '0',
1 => '0',
],
'size' => [
0 => '123',
1 => '7349',
],
],
'nested' => [
'name' => [
'other' => 'Flag.txt',
'test' => [
0 => 'Stuff.txt',
1 => '',
],
],
'type' => [
'other' => 'text/plain',
'test' => [
0 => 'text/plain',
1 => '',
],
],
'tmp_name' => [
'other' => '/tmp/php/hp9hskjhf',
'test' => [
0 => '/tmp/php/asifu2gp3',
1 => '',
],
],
'error' => [
'other' => '0',
'test' => [
0 => '0',
1 => '4',
],
],
'size' => [
'other' => '421',
'test' => [
0 => '32',
1 => '0',
]
]
],
],
[
'file' => [
0 => new UploadedFile(
'/tmp/php/hp9hskjhf',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
1 => new UploadedFile(
'/tmp/php/php1h4j1o',
7349,
UPLOAD_ERR_OK,
'Image.png',
'image/png'
),
],
'nested' => [
'other' => new UploadedFile(
'/tmp/php/hp9hskjhf',
421,
UPLOAD_ERR_OK,
'Flag.txt',
'text/plain'
),
'test' => [
0 => new UploadedFile(
'/tmp/php/asifu2gp3',
32,
UPLOAD_ERR_OK,
'Stuff.txt',
'text/plain'
),
1 => new UploadedFile(
'',
0,
UPLOAD_ERR_NO_FILE,
'',
''
),
]
]
]
]
];
}
/**
* @dataProvider dataNormalizeFiles
*/
public function testNormalizeFiles($files, $expected)
{
$result = ServerRequest::normalizeFiles($files);
self::assertEquals($expected, $result);
}
public function testNormalizeFilesRaisesException()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid value in files specification');
ServerRequest::normalizeFiles(['test' => 'something']);
}
public function dataGetUriFromGlobals()
{
$server = [
'REQUEST_URI' => '/blog/article.php?id=10&user=foo',
'SERVER_PORT' => '443',
'SERVER_ADDR' => '217.112.82.20',
'SERVER_NAME' => 'www.example.org',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_METHOD' => 'POST',
'QUERY_STRING' => 'id=10&user=foo',
'DOCUMENT_ROOT' => '/path/to/your/server/root/',
'HTTP_HOST' => 'www.example.org',
'HTTPS' => 'on',
'REMOTE_ADDR' => '193.60.168.69',
'REMOTE_PORT' => '5390',
'SCRIPT_NAME' => '/blog/article.php',
'SCRIPT_FILENAME' => '/path/to/your/server/root/blog/article.php',
'PHP_SELF' => '/blog/article.php',
];
return [
'HTTPS request' => [
'https://www.example.org/blog/article.php?id=10&user=foo',
$server,
],
'HTTPS request with different on value' => [
'https://www.example.org/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTPS' => '1']),
],
'HTTP request' => [
'http://www.example.org/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTPS' => 'off', 'SERVER_PORT' => '80']),
],
'HTTP_HOST missing -> fallback to SERVER_NAME' => [
'https://www.example.org/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => null]),
],
'HTTP_HOST and SERVER_NAME missing -> fallback to SERVER_ADDR' => [
'https://217.112.82.20/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => null, 'SERVER_NAME' => null]),
],
'Query string with ?' => [
'https://www.example.org/path?continue=https://example.com/path?param=1',
array_merge($server, ['REQUEST_URI' => '/path?continue=https://example.com/path?param=1', 'QUERY_STRING' => '']),
],
'No query String' => [
'https://www.example.org/blog/article.php',
array_merge($server, ['REQUEST_URI' => '/blog/article.php', 'QUERY_STRING' => '']),
],
'Host header with port' => [
'https://www.example.org:8324/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => 'www.example.org:8324']),
],
'IPv6 local loopback address' => [
'https://[::1]:8000/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => '[::1]:8000']),
],
'Invalid host' => [
'https://localhost/blog/article.php?id=10&user=foo',
array_merge($server, ['HTTP_HOST' => 'a:b']),
],
'Different port with SERVER_PORT' => [
'https://www.example.org:8324/blog/article.php?id=10&user=foo',
array_merge($server, ['SERVER_PORT' => '8324']),
],
'REQUEST_URI missing query string' => [
'https://www.example.org/blog/article.php?id=10&user=foo',
array_merge($server, ['REQUEST_URI' => '/blog/article.php']),
],
'Empty server variable' => [
'http://localhost',
[],
],
];
}
/**
* @dataProvider dataGetUriFromGlobals
*/
public function testGetUriFromGlobals($expected, $serverParams)
{
$_SERVER = $serverParams;
self::assertEquals(new Uri($expected), ServerRequest::getUriFromGlobals());
}
public function testFromGlobals()
{
$_SERVER = [
'REQUEST_URI' => '/blog/article.php?id=10&user=foo',
'SERVER_PORT' => '443',
'SERVER_ADDR' => '217.112.82.20',
'SERVER_NAME' => 'www.example.org',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_METHOD' => 'POST',
'QUERY_STRING' => 'id=10&user=foo',
'DOCUMENT_ROOT' => '/path/to/your/server/root/',
'CONTENT_TYPE' => 'text/plain',
'HTTP_HOST' => 'www.example.org',
'HTTP_ACCEPT' => 'text/html',
'HTTP_REFERRER' => 'https://example.com',
'HTTP_USER_AGENT' => 'My User Agent',
'HTTPS' => 'on',
'REMOTE_ADDR' => '193.60.168.69',
'REMOTE_PORT' => '5390',
'SCRIPT_NAME' => '/blog/article.php',
'SCRIPT_FILENAME' => '/path/to/your/server/root/blog/article.php',
'PHP_SELF' => '/blog/article.php',
];
$_COOKIE = [
'logged-in' => 'yes!'
];
$_POST = [
'name' => 'Pesho',
'email' => 'pesho@example.com',
];
$_GET = [
'id' => 10,
'user' => 'foo',
];
$_FILES = [
'file' => [
'name' => 'MyFile.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/php/php1h4j1o',
'error' => UPLOAD_ERR_OK,
'size' => 123,
]
];
$server = ServerRequest::fromGlobals();
self::assertSame('POST', $server->getMethod());
self::assertEquals([
'Host' => ['www.example.org'],
'Content-Type' => ['text/plain'],
'Accept' => ['text/html'],
'Referrer' => ['https://example.com'],
'User-Agent' => ['My User Agent'],
], $server->getHeaders());
self::assertSame('', (string) $server->getBody());
self::assertSame('1.1', $server->getProtocolVersion());
self::assertSame($_COOKIE, $server->getCookieParams());
self::assertSame($_POST, $server->getParsedBody());
self::assertSame($_GET, $server->getQueryParams());
self::assertEquals(
new Uri('https://www.example.org/blog/article.php?id=10&user=foo'),
$server->getUri()
);
$expectedFiles = [
'file' => new UploadedFile(
'/tmp/php/php1h4j1o',
123,
UPLOAD_ERR_OK,
'MyFile.txt',
'text/plain'
),
];
self::assertEquals($expectedFiles, $server->getUploadedFiles());
}
public function testUploadedFiles()
{
$request1 = new ServerRequest('GET', '/');
$files = [
'file' => new UploadedFile('test', 123, UPLOAD_ERR_OK)
];
$request2 = $request1->withUploadedFiles($files);
self::assertNotSame($request2, $request1);
self::assertSame([], $request1->getUploadedFiles());
self::assertSame($files, $request2->getUploadedFiles());
}
public function testServerParams()
{
$params = ['name' => 'value'];
$request = new ServerRequest('GET', '/', [], null, '1.1', $params);
self::assertSame($params, $request->getServerParams());
}
public function testCookieParams()
{
$request1 = new ServerRequest('GET', '/');
$params = ['name' => 'value'];
$request2 = $request1->withCookieParams($params);
self::assertNotSame($request2, $request1);
self::assertEmpty($request1->getCookieParams());
self::assertSame($params, $request2->getCookieParams());
}
public function testQueryParams()
{
$request1 = new ServerRequest('GET', '/');
$params = ['name' => 'value'];
$request2 = $request1->withQueryParams($params);
self::assertNotSame($request2, $request1);
self::assertEmpty($request1->getQueryParams());
self::assertSame($params, $request2->getQueryParams());
}
public function testParsedBody()
{
$request1 = new ServerRequest('GET', '/');
$params = ['name' => 'value'];
$request2 = $request1->withParsedBody($params);
self::assertNotSame($request2, $request1);
self::assertEmpty($request1->getParsedBody());
self::assertSame($params, $request2->getParsedBody());
}
public function testAttributes()
{
$request1 = new ServerRequest('GET', '/');
$request2 = $request1->withAttribute('name', 'value');
$request3 = $request2->withAttribute('other', 'otherValue');
$request4 = $request3->withoutAttribute('other');
$request5 = $request3->withoutAttribute('unknown');
self::assertNotSame($request2, $request1);
self::assertNotSame($request3, $request2);
self::assertNotSame($request4, $request3);
self::assertSame($request5, $request3);
self::assertSame([], $request1->getAttributes());
self::assertNull($request1->getAttribute('name'));
self::assertSame(
'something',
$request1->getAttribute('name', 'something'),
'Should return the default value'
);
self::assertSame('value', $request2->getAttribute('name'));
self::assertSame(['name' => 'value'], $request2->getAttributes());
self::assertEquals(['name' => 'value', 'other' => 'otherValue'], $request3->getAttributes());
self::assertSame(['name' => 'value'], $request4->getAttributes());
}
public function testNullAttribute()
{
$request = (new ServerRequest('GET', '/'))->withAttribute('name', null);
self::assertSame(['name' => null], $request->getAttributes());
self::assertNull($request->getAttribute('name', 'different-default'));
$requestWithoutAttribute = $request->withoutAttribute('name');
self::assertSame([], $requestWithoutAttribute->getAttributes());
self::assertSame('different-default', $requestWithoutAttribute->getAttribute('name', 'different-default'));
}
}

View File

@ -0,0 +1,147 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
class Str implements StreamInterface
{
use StreamDecoratorTrait;
}
/**
* @covers GuzzleHttp\Psr7\StreamDecoratorTrait
*/
class StreamDecoratorTraitTest extends BaseTest
{
/** @var StreamInterface */
private $a;
/** @var StreamInterface */
private $b;
/** @var resource */
private $c;
/**
* @before
*/
public function setUpTest()
{
$this->c = fopen('php://temp', 'r+');
fwrite($this->c, 'foo');
fseek($this->c, 0);
$this->a = Psr7\Utils::streamFor($this->c);
$this->b = new Str($this->a);
}
public function testCatchesExceptionsWhenCastingToString()
{
$s = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['read'])
->getMockForAbstractClass();
$s->expects(self::once())
->method('read')
->will(self::throwException(new \Exception('foo')));
$msg = '';
set_error_handler(function ($errNo, $str) use (&$msg) {
$msg = $str;
});
echo new Str($s);
restore_error_handler();
$this->assertStringContainsStringGuzzle('foo', $msg);
}
public function testToString()
{
self::assertSame('foo', (string) $this->b);
}
public function testHasSize()
{
self::assertSame(3, $this->b->getSize());
}
public function testReads()
{
self::assertSame('foo', $this->b->read(10));
}
public function testCheckMethods()
{
self::assertSame($this->a->isReadable(), $this->b->isReadable());
self::assertSame($this->a->isWritable(), $this->b->isWritable());
self::assertSame($this->a->isSeekable(), $this->b->isSeekable());
}
public function testSeeksAndTells()
{
$this->b->seek(1);
self::assertSame(1, $this->a->tell());
self::assertSame(1, $this->b->tell());
$this->b->seek(0);
self::assertSame(0, $this->a->tell());
self::assertSame(0, $this->b->tell());
$this->b->seek(0, SEEK_END);
self::assertSame(3, $this->a->tell());
self::assertSame(3, $this->b->tell());
}
public function testGetsContents()
{
self::assertSame('foo', $this->b->getContents());
self::assertSame('', $this->b->getContents());
$this->b->seek(1);
self::assertSame('oo', $this->b->getContents());
}
public function testCloses()
{
$this->b->close();
self::assertFalse(is_resource($this->c));
}
public function testDetaches()
{
$this->b->detach();
self::assertFalse($this->b->isReadable());
}
public function testWrapsMetadata()
{
self::assertSame($this->b->getMetadata(), $this->a->getMetadata());
self::assertSame($this->b->getMetadata('uri'), $this->a->getMetadata('uri'));
}
public function testWrapsWrites()
{
$this->b->seek(0, SEEK_END);
$this->b->write('foo');
self::assertSame('foofoo', (string) $this->a);
}
public function testThrowsWithInvalidGetter()
{
$this->expectExceptionGuzzle('UnexpectedValueException');
$this->b->foo;
}
public function testThrowsWhenGetterNotImplemented()
{
$s = new BadStream();
$this->expectExceptionGuzzle('BadMethodCallException');
$s->stream;
}
}
class BadStream
{
use StreamDecoratorTrait;
public function __construct()
{
}
}

View File

@ -0,0 +1,403 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Stream;
/**
* @covers GuzzleHttp\Psr7\Stream
*/
class StreamTest extends BaseTest
{
public static $isFReadError = false;
public function testConstructorThrowsExceptionOnInvalidArgument()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new Stream(true);
}
public function testConstructorInitializesProperties()
{
$handle = fopen('php://temp', 'r+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertTrue($stream->isReadable());
self::assertTrue($stream->isWritable());
self::assertTrue($stream->isSeekable());
self::assertSame('php://temp', $stream->getMetadata('uri'));
$this->assertInternalTypeGuzzle('array', $stream->getMetadata());
self::assertSame(4, $stream->getSize());
self::assertFalse($stream->eof());
$stream->close();
}
public function testConstructorInitializesPropertiesWithRbPlus()
{
$handle = fopen('php://temp', 'rb+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertTrue($stream->isReadable());
self::assertTrue($stream->isWritable());
self::assertTrue($stream->isSeekable());
self::assertSame('php://temp', $stream->getMetadata('uri'));
$this->assertInternalTypeGuzzle('array', $stream->getMetadata());
self::assertSame(4, $stream->getSize());
self::assertFalse($stream->eof());
$stream->close();
}
public function testStreamClosesHandleOnDestruct()
{
$handle = fopen('php://temp', 'r');
$stream = new Stream($handle);
unset($stream);
self::assertFalse(is_resource($handle));
}
public function testConvertsToString()
{
$handle = fopen('php://temp', 'w+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertSame('data', (string) $stream);
self::assertSame('data', (string) $stream);
$stream->close();
}
public function testConvertsToStringNonSeekableStream()
{
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$handle = popen('echo foo', 'r');
$stream = new Stream($handle);
self::assertFalse($stream->isSeekable());
self::assertSame('foo', trim((string) $stream));
}
public function testConvertsToStringNonSeekablePartiallyReadStream()
{
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$handle = popen('echo bar', 'r');
$stream = new Stream($handle);
$firstLetter = $stream->read(1);
self::assertFalse($stream->isSeekable());
self::assertSame('b', $firstLetter);
self::assertSame('ar', trim((string) $stream));
}
public function testGetsContents()
{
$handle = fopen('php://temp', 'w+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertSame('', $stream->getContents());
$stream->seek(0);
self::assertSame('data', $stream->getContents());
self::assertSame('', $stream->getContents());
$stream->close();
}
public function testChecksEof()
{
$handle = fopen('php://temp', 'w+');
fwrite($handle, 'data');
$stream = new Stream($handle);
self::assertSame(4, $stream->tell(), 'Stream cursor already at the end');
self::assertFalse($stream->eof(), 'Stream still not eof');
self::assertSame('', $stream->read(1), 'Need to read one more byte to reach eof');
self::assertTrue($stream->eof());
$stream->close();
}
public function testGetSize()
{
$size = filesize(__FILE__);
$handle = fopen(__FILE__, 'r');
$stream = new Stream($handle);
self::assertSame($size, $stream->getSize());
// Load from cache
self::assertSame($size, $stream->getSize());
$stream->close();
}
public function testEnsuresSizeIsConsistent()
{
$h = fopen('php://temp', 'w+');
self::assertSame(3, fwrite($h, 'foo'));
$stream = new Stream($h);
self::assertSame(3, $stream->getSize());
self::assertSame(4, $stream->write('test'));
self::assertSame(7, $stream->getSize());
self::assertSame(7, $stream->getSize());
$stream->close();
}
public function testProvidesStreamPosition()
{
$handle = fopen('php://temp', 'w+');
$stream = new Stream($handle);
self::assertSame(0, $stream->tell());
$stream->write('foo');
self::assertSame(3, $stream->tell());
$stream->seek(1);
self::assertSame(1, $stream->tell());
self::assertSame(ftell($handle), $stream->tell());
$stream->close();
}
public function testDetachStreamAndClearProperties()
{
$handle = fopen('php://temp', 'r');
$stream = new Stream($handle);
self::assertSame($handle, $stream->detach());
$this->assertInternalTypeGuzzle('resource', $handle, 'Stream is not closed');
self::assertNull($stream->detach());
$this->assertStreamStateAfterClosedOrDetached($stream);
$stream->close();
}
public function testCloseResourceAndClearProperties()
{
$handle = fopen('php://temp', 'r');
$stream = new Stream($handle);
$stream->close();
self::assertFalse(is_resource($handle));
$this->assertStreamStateAfterClosedOrDetached($stream);
}
private function assertStreamStateAfterClosedOrDetached(Stream $stream)
{
self::assertFalse($stream->isReadable());
self::assertFalse($stream->isWritable());
self::assertFalse($stream->isSeekable());
self::assertNull($stream->getSize());
self::assertSame([], $stream->getMetadata());
self::assertNull($stream->getMetadata('foo'));
$throws = function (callable $fn) {
try {
$fn();
} catch (\Exception $e) {
$this->assertStringContainsStringGuzzle('Stream is detached', $e->getMessage());
return;
}
$this->fail('Exception should be thrown after the stream is detached.');
};
$throws(function () use ($stream) {
$stream->read(10);
});
$throws(function () use ($stream) {
$stream->write('bar');
});
$throws(function () use ($stream) {
$stream->seek(10);
});
$throws(function () use ($stream) {
$stream->tell();
});
$throws(function () use ($stream) {
$stream->eof();
});
$throws(function () use ($stream) {
$stream->getContents();
});
self::assertSame('', (string) $stream);
}
public function testStreamReadingWithZeroLength()
{
$r = fopen('php://temp', 'r');
$stream = new Stream($r);
self::assertSame('', $stream->read(0));
$stream->close();
}
public function testStreamReadingWithNegativeLength()
{
$r = fopen('php://temp', 'r');
$stream = new Stream($r);
$this->expectExceptionGuzzle('RuntimeException', 'Length parameter cannot be negative');
try {
$stream->read(-1);
} catch (\Exception $e) {
$stream->close();
throw $e;
}
$stream->close();
}
public function testStreamReadingFreadError()
{
self::$isFReadError = true;
$r = fopen('php://temp', 'r');
$stream = new Stream($r);
$this->expectExceptionGuzzle('RuntimeException', 'Unable to read from stream');
try {
$stream->read(1);
} catch (\Exception $e) {
self::$isFReadError = false;
$stream->close();
throw $e;
}
self::$isFReadError = false;
$stream->close();
}
/**
* @dataProvider gzipModeProvider
*
* @param string $mode
* @param bool $readable
* @param bool $writable
*/
public function testGzipStreamModes($mode, $readable, $writable)
{
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$r = gzopen('php://temp', $mode);
$stream = new Stream($r);
self::assertSame($readable, $stream->isReadable());
self::assertSame($writable, $stream->isWritable());
$stream->close();
}
public function gzipModeProvider()
{
return [
['mode' => 'rb9', 'readable' => true, 'writable' => false],
['mode' => 'wb2', 'readable' => false, 'writable' => true],
];
}
/**
* @dataProvider readableModeProvider
*
* @param string $mode
*/
public function testReadableStream($mode)
{
$r = fopen('php://temp', $mode);
$stream = new Stream($r);
self::assertTrue($stream->isReadable());
$stream->close();
}
public function readableModeProvider()
{
return [
['r'],
['w+'],
['r+'],
['x+'],
['c+'],
['rb'],
['w+b'],
['r+b'],
['x+b'],
['c+b'],
['rt'],
['w+t'],
['r+t'],
['x+t'],
['c+t'],
['a+'],
['rb+'],
];
}
public function testWriteOnlyStreamIsNotReadable()
{
$r = fopen('php://output', 'w');
$stream = new Stream($r);
self::assertFalse($stream->isReadable());
$stream->close();
}
/**
* @dataProvider writableModeProvider
*
* @param string $mode
*/
public function testWritableStream($mode)
{
$r = fopen('php://temp', $mode);
$stream = new Stream($r);
self::assertTrue($stream->isWritable());
$stream->close();
}
public function writableModeProvider()
{
return [
['w'],
['w+'],
['rw'],
['r+'],
['x+'],
['c+'],
['wb'],
['w+b'],
['r+b'],
['rb+'],
['x+b'],
['c+b'],
['w+t'],
['r+t'],
['x+t'],
['c+t'],
['a'],
['a+'],
];
}
public function testReadOnlyStreamIsNotWritable()
{
$r = fopen('php://input', 'r');
$stream = new Stream($r);
self::assertFalse($stream->isWritable());
$stream->close();
}
}
namespace GuzzleHttp\Psr7;
use GuzzleHttp\Tests\Psr7\StreamTest;
function fread($handle, $length)
{
return StreamTest::$isFReadError ? false : \fread($handle, $length);
}

View File

@ -0,0 +1,200 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\StreamWrapper;
/**
* @covers GuzzleHttp\Psr7\StreamWrapper
*/
class StreamWrapperTest extends BaseTest
{
public function testResource()
{
$stream = Psr7\Utils::streamFor('foo');
$handle = StreamWrapper::getResource($stream);
self::assertSame('foo', fread($handle, 3));
self::assertSame(3, ftell($handle));
self::assertSame(3, fwrite($handle, 'bar'));
self::assertSame(0, fseek($handle, 0));
self::assertSame('foobar', fread($handle, 6));
self::assertSame('', fread($handle, 1));
self::assertTrue(feof($handle));
$stBlksize = defined('PHP_WINDOWS_VERSION_BUILD') ? -1 : 0;
// This fails on HHVM for some reason
if (!defined('HHVM_VERSION')) {
self::assertSame([
0 => 0,
1 => 0,
2 => 33206,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 6,
8 => 0,
9 => 0,
10 => 0,
11 => $stBlksize,
12 => $stBlksize,
'dev' => 0,
'ino' => 0,
'mode' => 33206,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => 6,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => $stBlksize,
'blocks' => $stBlksize,
], fstat($handle));
}
self::assertTrue(fclose($handle));
self::assertSame('foobar', (string) $stream);
}
public function testStreamContext()
{
$stream = Psr7\Utils::streamFor('foo');
self::assertSame('foo', file_get_contents('guzzle://stream', false, StreamWrapper::createStreamContext($stream)));
}
public function testStreamCast()
{
$streams = [
StreamWrapper::getResource(Psr7\Utils::streamFor('foo')),
StreamWrapper::getResource(Psr7\Utils::streamFor('bar'))
];
$write = null;
$except = null;
$this->assertInternalTypeGuzzle('integer', stream_select($streams, $write, $except, 0));
}
public function testValidatesStream()
{
$stream = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isReadable', 'isWritable'])
->getMockForAbstractClass();
$stream->expects(self::once())
->method('isReadable')
->will(self::returnValue(false));
$stream->expects(self::once())
->method('isWritable')
->will(self::returnValue(false));
$this->expectExceptionGuzzle('InvalidArgumentException');
StreamWrapper::getResource($stream);
}
public function testReturnsFalseWhenStreamDoesNotExist()
{
$this->expectWarningGuzzle();
fopen('guzzle://foo', 'r');
}
public function testCanOpenReadonlyStream()
{
$stream = $this->getMockBuilder('Psr\Http\Message\StreamInterface')
->setMethods(['isReadable', 'isWritable'])
->getMockForAbstractClass();
$stream->expects(self::once())
->method('isReadable')
->will(self::returnValue(false));
$stream->expects(self::once())
->method('isWritable')
->will(self::returnValue(true));
$r = StreamWrapper::getResource($stream);
$this->assertInternalTypeGuzzle('resource', $r);
fclose($r);
}
public function testUrlStat()
{
StreamWrapper::register();
$stBlksize = defined('PHP_WINDOWS_VERSION_BUILD') ? -1 : 0;
self::assertSame([
0 => 0,
1 => 0,
2 => 0,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
11 => $stBlksize,
12 => $stBlksize,
'dev' => 0,
'ino' => 0,
'mode' => 0,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => $stBlksize,
'blocks' => $stBlksize,
], stat('guzzle://stream'));
}
public function testXmlReaderWithStream()
{
if (!class_exists('XMLReader')) {
self::markTestSkipped('XML Reader is not available.');
}
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$stream = Psr7\Utils::streamFor('<?xml version="1.0" encoding="utf-8"?><foo />');
StreamWrapper::register();
libxml_set_streams_context(StreamWrapper::createStreamContext($stream));
$reader = new \XMLReader();
self::assertTrue($reader->open('guzzle://stream'));
self::assertTrue($reader->read());
self::assertSame('foo', $reader->name);
}
public function testXmlWriterWithStream()
{
if (!class_exists('XMLWriter')) {
self::markTestSkipped('XML Writer is not available.');
}
if (defined('HHVM_VERSION')) {
self::markTestSkipped('This does not work on HHVM.');
}
$stream = Psr7\Utils::streamFor(fopen('php://memory', 'wb'));
StreamWrapper::register();
libxml_set_streams_context(StreamWrapper::createStreamContext($stream));
$writer = new \XMLWriter();
self::assertTrue($writer->openURI('guzzle://stream'));
self::assertTrue($writer->startDocument());
self::assertTrue($writer->writeElement('foo'));
self::assertTrue($writer->endDocument());
$stream->rewind();
self::assertXmlStringEqualsXmlString('<?xml version="1.0"?><foo />', (string) $stream);
}
}

View File

@ -0,0 +1,287 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Stream;
use GuzzleHttp\Psr7\UploadedFile;
use ReflectionProperty;
/**
* @covers GuzzleHttp\Psr7\UploadedFile
*/
class UploadedFileTest extends BaseTest
{
private $cleanup;
/**
* @before
*/
public function setUpTest()
{
$this->cleanup = [];
}
/**
* @after
*/
public function tearDownTest()
{
foreach ($this->cleanup as $file) {
if (is_scalar($file) && file_exists($file)) {
unlink($file);
}
}
}
public function invalidStreams()
{
return [
'null' => [null],
'true' => [true],
'false' => [false],
'int' => [1],
'float' => [1.1],
'array' => [['filename']],
'object' => [(object) ['filename']],
];
}
/**
* @dataProvider invalidStreams
*/
public function testRaisesExceptionOnInvalidStreamOrFile($streamOrFile)
{
$this->expectExceptionGuzzle('InvalidArgumentException');
new UploadedFile($streamOrFile, 0, UPLOAD_ERR_OK);
}
public function invalidSizes()
{
return [
'null' => [null],
'float' => [1.1],
'array' => [[1]],
'object' => [(object) [1]],
];
}
/**
* @dataProvider invalidSizes
*/
public function testRaisesExceptionOnInvalidSize($size)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'size');
new UploadedFile(fopen('php://temp', 'wb+'), $size, UPLOAD_ERR_OK);
}
public function invalidErrorStatuses()
{
return [
'null' => [null],
'true' => [true],
'false' => [false],
'float' => [1.1],
'string' => ['1'],
'array' => [[1]],
'object' => [(object) [1]],
'negative' => [-1],
'too-big' => [9],
];
}
/**
* @dataProvider invalidErrorStatuses
*/
public function testRaisesExceptionOnInvalidErrorStatus($status)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'status');
new UploadedFile(fopen('php://temp', 'wb+'), 0, $status);
}
public function invalidFilenamesAndMediaTypes()
{
return [
'true' => [true],
'false' => [false],
'int' => [1],
'float' => [1.1],
'array' => [['string']],
'object' => [(object) ['string']],
];
}
/**
* @dataProvider invalidFilenamesAndMediaTypes
*/
public function testRaisesExceptionOnInvalidClientFilename($filename)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'filename');
new UploadedFile(fopen('php://temp', 'wb+'), 0, UPLOAD_ERR_OK, $filename);
}
/**
* @dataProvider invalidFilenamesAndMediaTypes
*/
public function testRaisesExceptionOnInvalidClientMediaType($mediaType)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'media type');
new UploadedFile(fopen('php://temp', 'wb+'), 0, UPLOAD_ERR_OK, 'foobar.baz', $mediaType);
}
public function testGetStreamReturnsOriginalStreamObject()
{
$stream = new Stream(fopen('php://temp', 'r'));
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
self::assertSame($stream, $upload->getStream());
}
public function testGetStreamReturnsWrappedPhpStream()
{
$stream = fopen('php://temp', 'wb+');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$uploadStream = $upload->getStream()->detach();
self::assertSame($stream, $uploadStream);
}
public function testGetStreamReturnsStreamForFile()
{
$this->cleanup[] = $stream = tempnam(sys_get_temp_dir(), 'stream_file');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$uploadStream = $upload->getStream();
$r = new ReflectionProperty($uploadStream, 'filename');
$r->setAccessible(true);
self::assertSame($stream, $r->getValue($uploadStream));
}
public function testSuccessful()
{
$stream = \GuzzleHttp\Psr7\Utils::streamFor('Foo bar!');
$upload = new UploadedFile($stream, $stream->getSize(), UPLOAD_ERR_OK, 'filename.txt', 'text/plain');
self::assertSame($stream->getSize(), $upload->getSize());
self::assertSame('filename.txt', $upload->getClientFilename());
self::assertSame('text/plain', $upload->getClientMediaType());
$this->cleanup[] = $to = tempnam(sys_get_temp_dir(), 'successful');
$upload->moveTo($to);
self::assertFileExists($to);
self::assertSame($stream->__toString(), file_get_contents($to));
}
public function invalidMovePaths()
{
return [
'null' => [null],
'true' => [true],
'false' => [false],
'int' => [1],
'float' => [1.1],
'empty' => [''],
'array' => [['filename']],
'object' => [(object) ['filename']],
];
}
/**
* @dataProvider invalidMovePaths
*/
public function testMoveRaisesExceptionForInvalidPath($path)
{
$stream = \GuzzleHttp\Psr7\Utils::streamFor('Foo bar!');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$this->cleanup[] = $path;
$this->expectExceptionGuzzle('InvalidArgumentException', 'path');
$upload->moveTo($path);
}
public function testMoveCannotBeCalledMoreThanOnce()
{
$stream = \GuzzleHttp\Psr7\Utils::streamFor('Foo bar!');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$this->cleanup[] = $to = tempnam(sys_get_temp_dir(), 'diac');
$upload->moveTo($to);
self::assertFileExists($to);
$this->expectExceptionGuzzle('RuntimeException', 'moved');
$upload->moveTo($to);
}
public function testCannotRetrieveStreamAfterMove()
{
$stream = \GuzzleHttp\Psr7\Utils::streamFor('Foo bar!');
$upload = new UploadedFile($stream, 0, UPLOAD_ERR_OK);
$this->cleanup[] = $to = tempnam(sys_get_temp_dir(), 'diac');
$upload->moveTo($to);
self::assertFileExists($to);
$this->expectExceptionGuzzle('RuntimeException', 'moved');
$upload->getStream();
}
public function nonOkErrorStatus()
{
return [
'UPLOAD_ERR_INI_SIZE' => [ UPLOAD_ERR_INI_SIZE ],
'UPLOAD_ERR_FORM_SIZE' => [ UPLOAD_ERR_FORM_SIZE ],
'UPLOAD_ERR_PARTIAL' => [ UPLOAD_ERR_PARTIAL ],
'UPLOAD_ERR_NO_FILE' => [ UPLOAD_ERR_NO_FILE ],
'UPLOAD_ERR_NO_TMP_DIR' => [ UPLOAD_ERR_NO_TMP_DIR ],
'UPLOAD_ERR_CANT_WRITE' => [ UPLOAD_ERR_CANT_WRITE ],
'UPLOAD_ERR_EXTENSION' => [ UPLOAD_ERR_EXTENSION ],
];
}
/**
* @dataProvider nonOkErrorStatus
*/
public function testConstructorDoesNotRaiseExceptionForInvalidStreamWhenErrorStatusPresent($status)
{
$uploadedFile = new UploadedFile('not ok', 0, $status);
self::assertSame($status, $uploadedFile->getError());
}
/**
* @dataProvider nonOkErrorStatus
*/
public function testMoveToRaisesExceptionWhenErrorStatusPresent($status)
{
$uploadedFile = new UploadedFile('not ok', 0, $status);
$this->expectExceptionGuzzle('RuntimeException', 'upload error');
$uploadedFile->moveTo(__DIR__ . '/' . sha1(uniqid('', true)));
}
/**
* @dataProvider nonOkErrorStatus
*/
public function testGetStreamRaisesExceptionWhenErrorStatusPresent($status)
{
$uploadedFile = new UploadedFile('not ok', 0, $status);
$this->expectExceptionGuzzle('RuntimeException', 'upload error');
$uploadedFile->getStream();
}
public function testMoveToCreatesStreamIfOnlyAFilenameWasProvided()
{
$this->cleanup[] = $from = tempnam(sys_get_temp_dir(), 'copy_from');
$this->cleanup[] = $to = tempnam(sys_get_temp_dir(), 'copy_to');
copy(__FILE__, $from);
$uploadedFile = new UploadedFile($from, 100, UPLOAD_ERR_OK, basename($from), 'text/plain');
$uploadedFile->moveTo($to);
self::assertFileEquals(__FILE__, $to);
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriComparator;
/**
* @covers GuzzleHttp\Psr7\UriComparator
*/
class UriComparatorTest extends BaseTest
{
/**
* @dataProvider getCrossOriginExamples
*/
public function testIsCrossOrigin($originalUri, $modifiedUri, $expected)
{
self::assertSame($expected, UriComparator::isCrossOrigin(new Uri($originalUri), new Uri($modifiedUri)));
}
public function getCrossOriginExamples()
{
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],
];
}
}

View File

@ -0,0 +1,176 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriNormalizer;
/**
* @covers GuzzleHttp\Psr7\UriNormalizer
*/
class UriNormalizerTest extends BaseTest
{
public function testCapitalizePercentEncoding()
{
$actualEncoding = 'a%c2%7A%5eb%25%fa%fA%Fa';
$expectEncoding = 'a%C2%7A%5Eb%25%FA%FA%FA';
$uri = (new Uri())->withPath("/$actualEncoding")->withQuery($actualEncoding);
self::assertSame("/$actualEncoding?$actualEncoding", (string) $uri, 'Not normalized automatically beforehand');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::CAPITALIZE_PERCENT_ENCODING);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame("/$expectEncoding?$expectEncoding", (string) $normalizedUri);
}
/**
* @dataProvider getUnreservedCharacters
*/
public function testDecodeUnreservedCharacters($char)
{
$percentEncoded = '%' . bin2hex($char);
// Add encoded reserved characters to test that those are not decoded and include the percent-encoded
// unreserved character both in lower and upper case to test the decoding is case-insensitive.
$encodedChars = $percentEncoded . '%2F%5B' . strtoupper($percentEncoded);
$uri = (new Uri())->withPath("/$encodedChars")->withQuery($encodedChars);
self::assertSame("/$encodedChars?$encodedChars", (string) $uri, 'Not normalized automatically beforehand');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::DECODE_UNRESERVED_CHARACTERS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame("/$char%2F%5B$char?$char%2F%5B$char", (string) $normalizedUri);
}
public function getUnreservedCharacters()
{
$unreservedChars = array_merge(range('a', 'z'), range('A', 'Z'), range('0', '9'), ['-', '.', '_', '~']);
return array_map(function ($char) {
return [$char];
}, $unreservedChars);
}
/**
* @dataProvider getEmptyPathTestCases
*/
public function testConvertEmptyPath($uri, $expected)
{
$normalizedUri = UriNormalizer::normalize(new Uri($uri), UriNormalizer::CONVERT_EMPTY_PATH);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame($expected, (string) $normalizedUri);
}
public function getEmptyPathTestCases()
{
return [
['http://example.org', 'http://example.org/'],
['https://example.org', 'https://example.org/'],
['urn://example.org', 'urn://example.org'],
];
}
public function testRemoveDefaultHost()
{
$uri = new Uri('file://localhost/myfile');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DEFAULT_HOST);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('file:///myfile', (string) $normalizedUri);
}
public function testRemoveDefaultPort()
{
$uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock();
$uri->expects(self::any())->method('getScheme')->will(self::returnValue('http'));
$uri->expects(self::any())->method('getPort')->will(self::returnValue(80));
$uri->expects(self::once())->method('withPort')->with(null)->will(self::returnValue(new Uri('http://example.org')));
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DEFAULT_PORT);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertNull($normalizedUri->getPort());
}
public function testRemoveDotSegments()
{
$uri = new Uri('http://example.org/../a/b/../c/./d.html');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DOT_SEGMENTS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('http://example.org/a/c/d.html', (string) $normalizedUri);
}
public function testRemoveDotSegmentsOfAbsolutePathReference()
{
$uri = new Uri('/../a/b/../c/./d.html');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DOT_SEGMENTS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('/a/c/d.html', (string) $normalizedUri);
}
public function testRemoveDotSegmentsOfRelativePathReference()
{
$uri = new Uri('../c/./d.html');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DOT_SEGMENTS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('../c/./d.html', (string) $normalizedUri);
}
public function testRemoveDuplicateSlashes()
{
$uri = new Uri('http://example.org//foo///bar/bam.html');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::REMOVE_DUPLICATE_SLASHES);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('http://example.org/foo/bar/bam.html', (string) $normalizedUri);
}
public function testSortQueryParameters()
{
$uri = new Uri('?lang=en&article=fred');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::SORT_QUERY_PARAMETERS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('?article=fred&lang=en', (string) $normalizedUri);
}
public function testSortQueryParametersWithSameKeys()
{
$uri = new Uri('?a=b&b=c&a=a&a&b=a&b=b&a=d&a=c');
$normalizedUri = UriNormalizer::normalize($uri, UriNormalizer::SORT_QUERY_PARAMETERS);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $normalizedUri);
self::assertSame('?a&a=a&a=b&a=c&a=d&b=a&b=b&b=c', (string) $normalizedUri);
}
/**
* @dataProvider getEquivalentTestCases
*/
public function testIsEquivalent($uri1, $uri2, $expected)
{
$equivalent = UriNormalizer::isEquivalent(new Uri($uri1), new Uri($uri2));
self::assertSame($expected, $equivalent);
}
public function getEquivalentTestCases()
{
return [
['http://example.org', 'http://example.org', true],
['hTTp://eXaMpLe.org', 'http://example.org', true],
['http://example.org/path?#', 'http://example.org/path', true],
['http://example.org:80', 'http://example.org/', true],
['http://example.org/../a/.././p%61th?%7a=%5e', 'http://example.org/path?z=%5E', true],
['https://example.org/', 'http://example.org/', false],
['https://example.org/', '//example.org/', false],
['//example.org/', '//example.org/', true],
['file:/myfile', 'file:///myfile', true],
['file:///myfile', 'file://localhost/myfile', true],
];
}
}

View File

@ -0,0 +1,204 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriResolver;
/**
* @covers GuzzleHttp\Psr7\UriResolver
*/
class UriResolverTest extends BaseTest
{
const RFC3986_BASE = 'http://a/b/c/d;p?q';
/**
* @dataProvider getResolveTestCases
*/
public function testResolveUri($base, $rel, $expectedTarget)
{
$baseUri = new Uri($base);
$targetUri = UriResolver::resolve($baseUri, new Uri($rel));
self::assertInstanceOf('Psr\Http\Message\UriInterface', $targetUri);
self::assertSame($expectedTarget, (string) $targetUri);
// This ensures there are no test cases that only work in the resolve() direction but not the
// opposite via relativize(). This can happen when both base and rel URI are relative-path
// references resulting in another relative-path URI.
self::assertSame($expectedTarget, (string) UriResolver::resolve($baseUri, $targetUri));
}
/**
* @dataProvider getResolveTestCases
*/
public function testRelativizeUri($base, $expectedRelativeReference, $target)
{
$baseUri = new Uri($base);
$relativeUri = UriResolver::relativize($baseUri, new Uri($target));
self::assertInstanceOf('Psr\Http\Message\UriInterface', $relativeUri);
// There are test-cases with too many dot-segments and relative references that are equal like "." == "./".
// So apart from the same-as condition, this alternative success condition is necessary.
self::assertTrue(
$expectedRelativeReference === (string) $relativeUri
|| $target === (string) UriResolver::resolve($baseUri, $relativeUri),
sprintf(
'"%s" is not the correct relative reference as it does not resolve to the target URI from the base URI',
(string) $relativeUri
)
);
}
/**
* @dataProvider getRelativizeTestCases
*/
public function testRelativizeUriWithUniqueTests($base, $target, $expectedRelativeReference)
{
$baseUri = new Uri($base);
$targetUri = new Uri($target);
$relativeUri = UriResolver::relativize($baseUri, $targetUri);
self::assertInstanceOf('Psr\Http\Message\UriInterface', $relativeUri);
self::assertSame($expectedRelativeReference, (string) $relativeUri);
self::assertSame((string) UriResolver::resolve($baseUri, $targetUri), (string) UriResolver::resolve($baseUri, $relativeUri));
}
public function getResolveTestCases()
{
return [
[self::RFC3986_BASE, 'g:h', 'g:h'],
[self::RFC3986_BASE, 'g', 'http://a/b/c/g'],
[self::RFC3986_BASE, './g', 'http://a/b/c/g'],
[self::RFC3986_BASE, 'g/', 'http://a/b/c/g/'],
[self::RFC3986_BASE, '/g', 'http://a/g'],
[self::RFC3986_BASE, '//g', 'http://g'],
[self::RFC3986_BASE, '?y', 'http://a/b/c/d;p?y'],
[self::RFC3986_BASE, 'g?y', 'http://a/b/c/g?y'],
[self::RFC3986_BASE, '#s', 'http://a/b/c/d;p?q#s'],
[self::RFC3986_BASE, 'g#s', 'http://a/b/c/g#s'],
[self::RFC3986_BASE, 'g?y#s', 'http://a/b/c/g?y#s'],
[self::RFC3986_BASE, ';x', 'http://a/b/c/;x'],
[self::RFC3986_BASE, 'g;x', 'http://a/b/c/g;x'],
[self::RFC3986_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s'],
[self::RFC3986_BASE, '', self::RFC3986_BASE],
[self::RFC3986_BASE, '.', 'http://a/b/c/'],
[self::RFC3986_BASE, './', 'http://a/b/c/'],
[self::RFC3986_BASE, '..', 'http://a/b/'],
[self::RFC3986_BASE, '../', 'http://a/b/'],
[self::RFC3986_BASE, '../g', 'http://a/b/g'],
[self::RFC3986_BASE, '../..', 'http://a/'],
[self::RFC3986_BASE, '../../', 'http://a/'],
[self::RFC3986_BASE, '../../g', 'http://a/g'],
[self::RFC3986_BASE, '../../../g', 'http://a/g'],
[self::RFC3986_BASE, '../../../../g', 'http://a/g'],
[self::RFC3986_BASE, '/./g', 'http://a/g'],
[self::RFC3986_BASE, '/../g', 'http://a/g'],
[self::RFC3986_BASE, 'g.', 'http://a/b/c/g.'],
[self::RFC3986_BASE, '.g', 'http://a/b/c/.g'],
[self::RFC3986_BASE, 'g..', 'http://a/b/c/g..'],
[self::RFC3986_BASE, '..g', 'http://a/b/c/..g'],
[self::RFC3986_BASE, './../g', 'http://a/b/g'],
[self::RFC3986_BASE, 'foo////g', 'http://a/b/c/foo////g'],
[self::RFC3986_BASE, './g/.', 'http://a/b/c/g/'],
[self::RFC3986_BASE, 'g/./h', 'http://a/b/c/g/h'],
[self::RFC3986_BASE, 'g/../h', 'http://a/b/c/h'],
[self::RFC3986_BASE, 'g;x=1/./y', 'http://a/b/c/g;x=1/y'],
[self::RFC3986_BASE, 'g;x=1/../y', 'http://a/b/c/y'],
// dot-segments in the query or fragment
[self::RFC3986_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x'],
[self::RFC3986_BASE, 'g?y/../x', 'http://a/b/c/g?y/../x'],
[self::RFC3986_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x'],
[self::RFC3986_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x'],
[self::RFC3986_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x'],
[self::RFC3986_BASE, '?y#s', 'http://a/b/c/d;p?y#s'],
// base with fragment
['http://a/b/c?q#s', '?y', 'http://a/b/c?y'],
// base with user info
['http://u@a/b/c/d;p?q', '.', 'http://u@a/b/c/'],
['http://u:p@a/b/c/d;p?q', '.', 'http://u:p@a/b/c/'],
// path ending with slash or no slash at all
['http://a/b/c/d/', 'e', 'http://a/b/c/d/e'],
['urn:no-slash', 'e', 'urn:e'],
// falsey relative parts
[self::RFC3986_BASE, '//0', 'http://0'],
[self::RFC3986_BASE, '0', 'http://a/b/c/0'],
[self::RFC3986_BASE, '?0', 'http://a/b/c/d;p?0'],
[self::RFC3986_BASE, '#0', 'http://a/b/c/d;p?q#0'],
// absolute path base URI
['/a/b/', '', '/a/b/'],
['/a/b', '', '/a/b'],
['/', 'a', '/a'],
['/', 'a/b', '/a/b'],
['/a/b', 'g', '/a/g'],
['/a/b/c', './', '/a/b/'],
['/a/b/', '../', '/a/'],
['/a/b/c', '../', '/a/'],
['/a/b/', '../../x/y/z/', '/x/y/z/'],
['/a/b/c/d/e', '../../../c/d', '/a/c/d'],
['/a/b/c//', '../', '/a/b/c/'],
['/a/b/c/', './/', '/a/b/c//'],
['/a/b/c', '../../../../a', '/a'],
['/a/b/c', '../../../..', '/'],
// not actually a dot-segment
['/a/b/c', '..a/b..', '/a/b/..a/b..'],
// '' cannot be used as relative reference as it would inherit the base query component
['/a/b?q', 'b', '/a/b'],
['/a/b/?q', './', '/a/b/'],
// path with colon: "with:colon" would be the wrong relative reference
['/a/', './with:colon', '/a/with:colon'],
['/a/', 'b/with:colon', '/a/b/with:colon'],
['/a/', './:b/', '/a/:b/'],
// relative path references
['a', 'a/b', 'a/b'],
['', '', ''],
['', '..', ''],
['/', '..', '/'],
['urn:a/b', '..//a/b', 'urn:/a/b'],
// network path references
// empty base path and relative-path reference
['//example.com', 'a', '//example.com/a'],
// path starting with two slashes
['//example.com//two-slashes', './', '//example.com//'],
['//example.com', './/', '//example.com//'],
['//example.com/', './/', '//example.com//'],
// base URI has less components than relative URI
['/', '//a/b?q#h', '//a/b?q#h'],
['/', 'urn:/', 'urn:/'],
];
}
/**
* Some additional tests to getResolveTestCases() that only make sense for relativize.
*/
public function getRelativizeTestCases()
{
return [
// targets that are relative-path references are returned as-is
['a/b', 'b/c', 'b/c'],
['a/b/c', '../b/c', '../b/c'],
['a', '', ''],
['a', './', './'],
['a', 'a/..', 'a/..'],
['/a/b/?q', '?q#h', '?q#h'],
['/a/b/?q', '#h', '#h'],
['/a/b/?q', 'c#h', 'c#h'],
// If the base URI has a query but the target has none, we cannot return an empty path reference as it would
// inherit the base query component when resolving.
['/a/b/?q', '/a/b/#h', './#h'],
['/', '/#h', '#h'],
['/', '/', ''],
['http://a', 'http://a/', './'],
['urn:a/b?q', 'urn:x/y?q', '../x/y?q'],
['urn:', 'urn:/', './/'],
['urn:a/b?q', 'urn:', '../'],
// target URI has less components than base URI
['http://a/b/', '//a/b/c', 'c'],
['http://a/b/', '/b/c', 'c'],
['http://a/b/', '/x/y', '../x/y'],
['http://a/b/', '/', '../'],
// absolute target URI without authority but base URI has one
['urn://a/b/', 'urn:/b/', 'urn:/b/'],
];
}
}

View File

@ -0,0 +1,710 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7\Uri;
/**
* @covers GuzzleHttp\Psr7\Uri
*/
class UriTest extends BaseTest
{
public function testParsesProvidedUri()
{
$uri = new Uri('https://user:pass@example.com:8080/path/123?q=abc#test');
self::assertSame('https', $uri->getScheme());
self::assertSame('user:pass@example.com:8080', $uri->getAuthority());
self::assertSame('user:pass', $uri->getUserInfo());
self::assertSame('example.com', $uri->getHost());
self::assertSame(8080, $uri->getPort());
self::assertSame('/path/123', $uri->getPath());
self::assertSame('q=abc', $uri->getQuery());
self::assertSame('test', $uri->getFragment());
self::assertSame('https://user:pass@example.com:8080/path/123?q=abc#test', (string) $uri);
}
public function testCanTransformAndRetrievePartsIndividually()
{
$uri = (new Uri())
->withScheme('https')
->withUserInfo('user', 'pass')
->withHost('example.com')
->withPort(8080)
->withPath('/path/123')
->withQuery('q=abc')
->withFragment('test');
self::assertSame('https', $uri->getScheme());
self::assertSame('user:pass@example.com:8080', $uri->getAuthority());
self::assertSame('user:pass', $uri->getUserInfo());
self::assertSame('example.com', $uri->getHost());
self::assertSame(8080, $uri->getPort());
self::assertSame('/path/123', $uri->getPath());
self::assertSame('q=abc', $uri->getQuery());
self::assertSame('test', $uri->getFragment());
self::assertSame('https://user:pass@example.com:8080/path/123?q=abc#test', (string) $uri);
}
/**
* @dataProvider getValidUris
*/
public function testValidUrisStayValid($input)
{
$uri = new Uri($input);
self::assertSame($input, (string) $uri);
}
/**
* @dataProvider getValidUris
*/
public function testFromParts($input)
{
$uri = Uri::fromParts(parse_url($input));
self::assertSame($input, (string) $uri);
}
public function getValidUris()
{
return [
['urn:path-rootless'],
['urn:path:with:colon'],
['urn:/path-absolute'],
['urn:/'],
// only scheme with empty path
['urn:'],
// only path
['/'],
['relative/'],
['0'],
// same document reference
[''],
// network path without scheme
['//example.org'],
['//example.org/'],
['//example.org?q#h'],
// only query
['?q'],
['?q=abc&foo=bar'],
// only fragment
['#fragment'],
// dot segments are not removed automatically
['./foo/../bar'],
];
}
/**
* @dataProvider getInvalidUris
*/
public function testInvalidUrisThrowException($invalidUri)
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Unable to parse URI');
new Uri($invalidUri);
}
public function getInvalidUris()
{
return [
// parse_url() requires the host component which makes sense for http(s)
// but not when the scheme is not known or different. So '//' or '///' is
// currently invalid as well but should not according to RFC 3986.
['http://'],
['urn://host:with:colon'], // host cannot contain ":"
];
}
public function testPortMustBeValid()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Must be between 0 and 65535');
(new Uri())->withPort(100000);
}
public function testWithPortCannotBeNegative()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Invalid port: -1. Must be between 0 and 65535');
(new Uri())->withPort(-1);
}
public function testParseUriPortCannotBeNegative()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'Unable to parse URI');
new Uri('//example.com:-1');
}
public function testSchemeMustHaveCorrectType()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
(new Uri())->withScheme([]);
}
public function testHostMustHaveCorrectType()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
(new Uri())->withHost([]);
}
public function testPathMustHaveCorrectType()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
(new Uri())->withPath([]);
}
public function testQueryMustHaveCorrectType()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
(new Uri())->withQuery([]);
}
public function testFragmentMustHaveCorrectType()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
(new Uri())->withFragment([]);
}
public function testCanParseFalseyUriParts()
{
$uri = new Uri('0://0:0@0/0?0#0');
self::assertSame('0', $uri->getScheme());
self::assertSame('0:0@0', $uri->getAuthority());
self::assertSame('0:0', $uri->getUserInfo());
self::assertSame('0', $uri->getHost());
self::assertSame('/0', $uri->getPath());
self::assertSame('0', $uri->getQuery());
self::assertSame('0', $uri->getFragment());
self::assertSame('0://0:0@0/0?0#0', (string) $uri);
}
public function testCanConstructFalseyUriParts()
{
$uri = (new Uri())
->withScheme('0')
->withUserInfo('0', '0')
->withHost('0')
->withPath('/0')
->withQuery('0')
->withFragment('0');
self::assertSame('0', $uri->getScheme());
self::assertSame('0:0@0', $uri->getAuthority());
self::assertSame('0:0', $uri->getUserInfo());
self::assertSame('0', $uri->getHost());
self::assertSame('/0', $uri->getPath());
self::assertSame('0', $uri->getQuery());
self::assertSame('0', $uri->getFragment());
self::assertSame('0://0:0@0/0?0#0', (string) $uri);
}
/**
* @dataProvider getPortTestCases
*/
public function testIsDefaultPort($scheme, $port, $isDefaultPort)
{
$uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock();
$uri->expects(self::any())->method('getScheme')->will(self::returnValue($scheme));
$uri->expects(self::any())->method('getPort')->will(self::returnValue($port));
self::assertSame($isDefaultPort, Uri::isDefaultPort($uri));
}
public function getPortTestCases()
{
return [
['http', null, true],
['http', 80, true],
['http', 8080, false],
['https', null, true],
['https', 443, true],
['https', 444, false],
['ftp', 21, true],
['gopher', 70, true],
['nntp', 119, true],
['news', 119, true],
['telnet', 23, true],
['tn3270', 23, true],
['imap', 143, true],
['pop', 110, true],
['ldap', 389, true],
];
}
public function testIsAbsolute()
{
self::assertTrue(Uri::isAbsolute(new Uri('http://example.org')));
self::assertFalse(Uri::isAbsolute(new Uri('//example.org')));
self::assertFalse(Uri::isAbsolute(new Uri('/abs-path')));
self::assertFalse(Uri::isAbsolute(new Uri('rel-path')));
}
public function testIsNetworkPathReference()
{
self::assertFalse(Uri::isNetworkPathReference(new Uri('http://example.org')));
self::assertTrue(Uri::isNetworkPathReference(new Uri('//example.org')));
self::assertFalse(Uri::isNetworkPathReference(new Uri('/abs-path')));
self::assertFalse(Uri::isNetworkPathReference(new Uri('rel-path')));
}
public function testIsAbsolutePathReference()
{
self::assertFalse(Uri::isAbsolutePathReference(new Uri('http://example.org')));
self::assertFalse(Uri::isAbsolutePathReference(new Uri('//example.org')));
self::assertTrue(Uri::isAbsolutePathReference(new Uri('/abs-path')));
self::assertTrue(Uri::isAbsolutePathReference(new Uri('/')));
self::assertFalse(Uri::isAbsolutePathReference(new Uri('rel-path')));
}
public function testIsRelativePathReference()
{
self::assertFalse(Uri::isRelativePathReference(new Uri('http://example.org')));
self::assertFalse(Uri::isRelativePathReference(new Uri('//example.org')));
self::assertFalse(Uri::isRelativePathReference(new Uri('/abs-path')));
self::assertTrue(Uri::isRelativePathReference(new Uri('rel-path')));
self::assertTrue(Uri::isRelativePathReference(new Uri('')));
}
public function testIsSameDocumentReference()
{
self::assertFalse(Uri::isSameDocumentReference(new Uri('http://example.org')));
self::assertFalse(Uri::isSameDocumentReference(new Uri('//example.org')));
self::assertFalse(Uri::isSameDocumentReference(new Uri('/abs-path')));
self::assertFalse(Uri::isSameDocumentReference(new Uri('rel-path')));
self::assertFalse(Uri::isSameDocumentReference(new Uri('?query')));
self::assertTrue(Uri::isSameDocumentReference(new Uri('')));
self::assertTrue(Uri::isSameDocumentReference(new Uri('#fragment')));
$baseUri = new Uri('http://example.org/path?foo=bar');
self::assertTrue(Uri::isSameDocumentReference(new Uri('#fragment'), $baseUri));
self::assertTrue(Uri::isSameDocumentReference(new Uri('?foo=bar#fragment'), $baseUri));
self::assertTrue(Uri::isSameDocumentReference(new Uri('/path?foo=bar#fragment'), $baseUri));
self::assertTrue(Uri::isSameDocumentReference(new Uri('path?foo=bar#fragment'), $baseUri));
self::assertTrue(Uri::isSameDocumentReference(new Uri('//example.org/path?foo=bar#fragment'), $baseUri));
self::assertTrue(Uri::isSameDocumentReference(new Uri('http://example.org/path?foo=bar#fragment'), $baseUri));
self::assertFalse(Uri::isSameDocumentReference(new Uri('https://example.org/path?foo=bar'), $baseUri));
self::assertFalse(Uri::isSameDocumentReference(new Uri('http://example.com/path?foo=bar'), $baseUri));
self::assertFalse(Uri::isSameDocumentReference(new Uri('http://example.org/'), $baseUri));
self::assertFalse(Uri::isSameDocumentReference(new Uri('http://example.org'), $baseUri));
self::assertFalse(Uri::isSameDocumentReference(new Uri('urn:/path'), new Uri('urn://example.com/path')));
}
public function testAddAndRemoveQueryValues()
{
$uri = new Uri();
$uri = Uri::withQueryValue($uri, 'a', 'b');
$uri = Uri::withQueryValue($uri, 'c', 'd');
$uri = Uri::withQueryValue($uri, 'e', null);
self::assertSame('a=b&c=d&e', $uri->getQuery());
$uri = Uri::withoutQueryValue($uri, 'c');
self::assertSame('a=b&e', $uri->getQuery());
$uri = Uri::withoutQueryValue($uri, 'e');
self::assertSame('a=b', $uri->getQuery());
$uri = Uri::withoutQueryValue($uri, 'a');
self::assertSame('', $uri->getQuery());
}
public function testNumericQueryValue()
{
$uri = Uri::withQueryValue(new Uri(), 'version', 1);
self::assertSame('version=1', $uri->getQuery());
}
public function testWithQueryValues()
{
$uri = new Uri();
$uri = Uri::withQueryValues($uri, [
'key1' => 'value1',
'key2' => 'value2'
]);
self::assertSame('key1=value1&key2=value2', $uri->getQuery());
}
public function testWithQueryValuesReplacesSameKeys()
{
$uri = new Uri();
$uri = Uri::withQueryValues($uri, [
'key1' => 'value1',
'key2' => 'value2'
]);
$uri = Uri::withQueryValues($uri, [
'key2' => 'newvalue'
]);
self::assertSame('key1=value1&key2=newvalue', $uri->getQuery());
}
public function testWithQueryValueReplacesSameKeys()
{
$uri = new Uri();
$uri = Uri::withQueryValue($uri, 'a', 'b');
$uri = Uri::withQueryValue($uri, 'c', 'd');
$uri = Uri::withQueryValue($uri, 'a', 'e');
self::assertSame('c=d&a=e', $uri->getQuery());
}
public function testWithoutQueryValueRemovesAllSameKeys()
{
$uri = (new Uri())->withQuery('a=b&c=d&a=e');
$uri = Uri::withoutQueryValue($uri, 'a');
self::assertSame('c=d', $uri->getQuery());
}
public function testRemoveNonExistingQueryValue()
{
$uri = new Uri();
$uri = Uri::withQueryValue($uri, 'a', 'b');
$uri = Uri::withoutQueryValue($uri, 'c');
self::assertSame('a=b', $uri->getQuery());
}
public function testWithQueryValueHandlesEncoding()
{
$uri = new Uri();
$uri = Uri::withQueryValue($uri, 'E=mc^2', 'ein&stein');
self::assertSame('E%3Dmc%5E2=ein%26stein', $uri->getQuery(), 'Decoded key/value get encoded');
$uri = new Uri();
$uri = Uri::withQueryValue($uri, 'E%3Dmc%5e2', 'ein%26stein');
self::assertSame('E%3Dmc%5e2=ein%26stein', $uri->getQuery(), 'Encoded key/value do not get double-encoded');
}
public function testWithoutQueryValueHandlesEncoding()
{
// It also tests that the case of the percent-encoding does not matter,
// i.e. both lowercase "%3d" and uppercase "%5E" can be removed.
$uri = (new Uri())->withQuery('E%3dmc%5E2=einstein&foo=bar');
$uri = Uri::withoutQueryValue($uri, 'E=mc^2');
self::assertSame('foo=bar', $uri->getQuery(), 'Handles key in decoded form');
$uri = (new Uri())->withQuery('E%3dmc%5E2=einstein&foo=bar');
$uri = Uri::withoutQueryValue($uri, 'E%3Dmc%5e2');
self::assertSame('foo=bar', $uri->getQuery(), 'Handles key in encoded form');
}
public function testSchemeIsNormalizedToLowercase()
{
$uri = new Uri('HTTP://example.com');
self::assertSame('http', $uri->getScheme());
self::assertSame('http://example.com', (string) $uri);
$uri = (new Uri('//example.com'))->withScheme('HTTP');
self::assertSame('http', $uri->getScheme());
self::assertSame('http://example.com', (string) $uri);
}
public function testHostIsNormalizedToLowercase()
{
$uri = new Uri('//eXaMpLe.CoM');
self::assertSame('example.com', $uri->getHost());
self::assertSame('//example.com', (string) $uri);
$uri = (new Uri())->withHost('eXaMpLe.CoM');
self::assertSame('example.com', $uri->getHost());
self::assertSame('//example.com', (string) $uri);
}
public function testPortIsNullIfStandardPortForScheme()
{
// HTTPS standard port
$uri = new Uri('https://example.com:443');
self::assertNull($uri->getPort());
self::assertSame('example.com', $uri->getAuthority());
$uri = (new Uri('https://example.com'))->withPort(443);
self::assertNull($uri->getPort());
self::assertSame('example.com', $uri->getAuthority());
// HTTP standard port
$uri = new Uri('http://example.com:80');
self::assertNull($uri->getPort());
self::assertSame('example.com', $uri->getAuthority());
$uri = (new Uri('http://example.com'))->withPort(80);
self::assertNull($uri->getPort());
self::assertSame('example.com', $uri->getAuthority());
}
public function testPortIsReturnedIfSchemeUnknown()
{
$uri = (new Uri('//example.com'))->withPort(80);
self::assertSame(80, $uri->getPort());
self::assertSame('example.com:80', $uri->getAuthority());
}
public function testStandardPortIsNullIfSchemeChanges()
{
$uri = new Uri('http://example.com:443');
self::assertSame('http', $uri->getScheme());
self::assertSame(443, $uri->getPort());
$uri = $uri->withScheme('https');
self::assertNull($uri->getPort());
}
public function testPortPassedAsStringIsCastedToInt()
{
$uri = (new Uri('//example.com'))->withPort('8080');
self::assertSame(8080, $uri->getPort(), 'Port is returned as integer');
self::assertSame('example.com:8080', $uri->getAuthority());
}
public function testPortCanBeRemoved()
{
$uri = (new Uri('http://example.com:8080'))->withPort(null);
self::assertNull($uri->getPort());
self::assertSame('http://example.com', (string) $uri);
}
/**
* In RFC 8986 the host is optional and the authority can only
* consist of the user info and port.
*/
public function testAuthorityWithUserInfoOrPortButWithoutHost()
{
$uri = (new Uri())->withUserInfo('user', 'pass');
self::assertSame('user:pass', $uri->getUserInfo());
self::assertSame('user:pass@', $uri->getAuthority());
$uri = $uri->withPort(8080);
self::assertSame(8080, $uri->getPort());
self::assertSame('user:pass@:8080', $uri->getAuthority());
self::assertSame('//user:pass@:8080', (string) $uri);
$uri = $uri->withUserInfo('');
self::assertSame(':8080', $uri->getAuthority());
}
public function testHostInHttpUriDefaultsToLocalhost()
{
$uri = (new Uri())->withScheme('http');
self::assertSame('localhost', $uri->getHost());
self::assertSame('localhost', $uri->getAuthority());
self::assertSame('http://localhost', (string) $uri);
}
public function testHostInHttpsUriDefaultsToLocalhost()
{
$uri = (new Uri())->withScheme('https');
self::assertSame('localhost', $uri->getHost());
self::assertSame('localhost', $uri->getAuthority());
self::assertSame('https://localhost', (string) $uri);
}
public function testFileSchemeWithEmptyHostReconstruction()
{
$uri = new Uri('file:///tmp/filename.ext');
self::assertSame('', $uri->getHost());
self::assertSame('', $uri->getAuthority());
self::assertSame('file:///tmp/filename.ext', (string) $uri);
}
public function uriComponentsEncodingProvider()
{
$unreserved = 'a-zA-Z0-9.-_~!$&\'()*+,;=:@';
return [
// Percent encode spaces
['/pa th?q=va lue#frag ment', '/pa%20th', 'q=va%20lue', 'frag%20ment', '/pa%20th?q=va%20lue#frag%20ment'],
// Percent encode multibyte
['/€?€#€', '/%E2%82%AC', '%E2%82%AC', '%E2%82%AC', '/%E2%82%AC?%E2%82%AC#%E2%82%AC'],
// Don't encode something that's already encoded
['/pa%20th?q=va%20lue#frag%20ment', '/pa%20th', 'q=va%20lue', 'frag%20ment', '/pa%20th?q=va%20lue#frag%20ment'],
// Percent encode invalid percent encodings
['/pa%2-th?q=va%2-lue#frag%2-ment', '/pa%252-th', 'q=va%252-lue', 'frag%252-ment', '/pa%252-th?q=va%252-lue#frag%252-ment'],
// Don't encode path segments
['/pa/th//two?q=va/lue#frag/ment', '/pa/th//two', 'q=va/lue', 'frag/ment', '/pa/th//two?q=va/lue#frag/ment'],
// Don't encode unreserved chars or sub-delimiters
["/$unreserved?$unreserved#$unreserved", "/$unreserved", $unreserved, $unreserved, "/$unreserved?$unreserved#$unreserved"],
// Encoded unreserved chars are not decoded
['/p%61th?q=v%61lue#fr%61gment', '/p%61th', 'q=v%61lue', 'fr%61gment', '/p%61th?q=v%61lue#fr%61gment'],
];
}
/**
* @dataProvider uriComponentsEncodingProvider
*/
public function testUriComponentsGetEncodedProperly($input, $path, $query, $fragment, $output)
{
$uri = new Uri($input);
self::assertSame($path, $uri->getPath());
self::assertSame($query, $uri->getQuery());
self::assertSame($fragment, $uri->getFragment());
self::assertSame($output, (string) $uri);
}
public function testWithPathEncodesProperly()
{
$uri = (new Uri())->withPath('/baz?#€/b%61r');
// Query and fragment delimiters and multibyte chars are encoded.
self::assertSame('/baz%3F%23%E2%82%AC/b%61r', $uri->getPath());
self::assertSame('/baz%3F%23%E2%82%AC/b%61r', (string) $uri);
}
public function testWithQueryEncodesProperly()
{
$uri = (new Uri())->withQuery('?=#&€=/&b%61r');
// A query starting with a "?" is valid and must not be magically removed. Otherwise it would be impossible to
// construct such an URI. Also the "?" and "/" does not need to be encoded in the query.
self::assertSame('?=%23&%E2%82%AC=/&b%61r', $uri->getQuery());
self::assertSame('??=%23&%E2%82%AC=/&b%61r', (string) $uri);
}
public function testWithFragmentEncodesProperly()
{
$uri = (new Uri())->withFragment('#€?/b%61r');
// A fragment starting with a "#" is valid and must not be magically removed. Otherwise it would be impossible to
// construct such an URI. Also the "?" and "/" does not need to be encoded in the fragment.
self::assertSame('%23%E2%82%AC?/b%61r', $uri->getFragment());
self::assertSame('#%23%E2%82%AC?/b%61r', (string) $uri);
}
public function testAllowsForRelativeUri()
{
$uri = (new Uri)->withPath('foo');
self::assertSame('foo', $uri->getPath());
self::assertSame('foo', (string) $uri);
}
public function testRelativePathAndAuhorityIsAutomagicallyFixed()
{
// concatenating a relative path with a host doesn't work: "//example.comfoo" would be wrong
$uri = (new Uri)->withPath('foo')->withHost('example.com');
self::assertSame('/foo', $uri->getPath());
self::assertSame('//example.com/foo', (string) $uri);
}
public function testPathStartingWithTwoSlashesAndNoAuthorityIsInvalid()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'The path of a URI without an authority must not start with two slashes "//"');
// URI "//foo" would be interpreted as network reference and thus change the original path to the host
(new Uri)->withPath('//foo');
}
public function testPathStartingWithTwoSlashes()
{
$uri = new Uri('http://example.org//path-not-host.com');
self::assertSame('//path-not-host.com', $uri->getPath());
$uri = $uri->withScheme('');
self::assertSame('//example.org//path-not-host.com', (string) $uri); // This is still valid
$this->expectExceptionGuzzle('\InvalidArgumentException');
$uri->withHost(''); // Now it becomes invalid
}
public function testRelativeUriWithPathBeginngWithColonSegmentIsInvalid()
{
$this->expectExceptionGuzzle('InvalidArgumentException', 'A relative URI must not have a path beginning with a segment containing a colon');
(new Uri)->withPath('mailto:foo');
}
public function testRelativeUriWithPathHavingColonSegment()
{
$uri = (new Uri('urn:/mailto:foo'))->withScheme('');
self::assertSame('/mailto:foo', $uri->getPath());
$this->expectExceptionGuzzle('\InvalidArgumentException');
(new Uri('urn:mailto:foo'))->withScheme('');
}
public function testDefaultReturnValuesOfGetters()
{
$uri = new Uri();
self::assertSame('', $uri->getScheme());
self::assertSame('', $uri->getAuthority());
self::assertSame('', $uri->getUserInfo());
self::assertSame('', $uri->getHost());
self::assertNull($uri->getPort());
self::assertSame('', $uri->getPath());
self::assertSame('', $uri->getQuery());
self::assertSame('', $uri->getFragment());
}
public function testImmutability()
{
$uri = new Uri();
self::assertNotSame($uri, $uri->withScheme('https'));
self::assertNotSame($uri, $uri->withUserInfo('user', 'pass'));
self::assertNotSame($uri, $uri->withHost('example.com'));
self::assertNotSame($uri, $uri->withPort(8080));
self::assertNotSame($uri, $uri->withPath('/path/123'));
self::assertNotSame($uri, $uri->withQuery('q=abc'));
self::assertNotSame($uri, $uri->withFragment('test'));
}
public function testExtendingClassesInstantiates()
{
// The non-standard port triggers a cascade of private methods which
// should not use late static binding to access private static members.
// If they do, this will fatal.
self::assertInstanceOf(
'GuzzleHttp\Tests\Psr7\ExtendedUriTest',
new ExtendedUriTest('http://h:9/')
);
}
public function testSpecialCharsOfUserInfo()
{
// The `userInfo` must always be URL-encoded.
$uri = (new Uri)->withUserInfo('foo@bar.com', 'pass#word');
self::assertSame('foo%40bar.com:pass%23word', $uri->getUserInfo());
// The `userInfo` can already be URL-encoded: it should not be encoded twice.
$uri = (new Uri)->withUserInfo('foo%40bar.com', 'pass%23word');
self::assertSame('foo%40bar.com:pass%23word', $uri->getUserInfo());
}
public function testInternationalizedDomainName()
{
$uri = new Uri('https://яндекс.рф');
self::assertSame('яндекс.рф', $uri->getHost());
$uri = new Uri('https://яндекAс.рф');
self::assertSame('яндекaс.рф', $uri->getHost());
}
public function testIPv6Host()
{
$uri = new Uri('https://[2a00:f48:1008::212:183:10]');
self::assertSame('[2a00:f48:1008::212:183:10]', $uri->getHost());
$uri = new Uri('http://[2a00:f48:1008::212:183:10]:56?foo=bar');
self::assertSame('[2a00:f48:1008::212:183:10]', $uri->getHost());
self::assertSame(56, $uri->getPort());
self::assertSame('foo=bar', $uri->getQuery());
}
}
class ExtendedUriTest extends Uri
{
}

View File

@ -0,0 +1,469 @@
<?php
namespace GuzzleHttp\Tests\Psr7;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\NoSeekStream;
class UtilsTest extends BaseTest
{
public function testCopiesToString()
{
$s = Psr7\Utils::streamFor('foobaz');
self::assertSame('foobaz', Psr7\Utils::copyToString($s));
$s->seek(0);
self::assertSame('foo', Psr7\Utils::copyToString($s, 3));
self::assertSame('baz', Psr7\Utils::copyToString($s, 3));
self::assertSame('', Psr7\Utils::copyToString($s));
}
public function testCopiesToStringStopsWhenReadFails()
{
$s1 = Psr7\Utils::streamFor('foobaz');
$s1 = FnStream::decorate($s1, [
'read' => function () {
return '';
},
]);
$result = Psr7\Utils::copyToString($s1);
self::assertSame('', $result);
}
public function testCopiesToStream()
{
$s1 = Psr7\Utils::streamFor('foobaz');
$s2 = Psr7\Utils::streamFor('');
Psr7\Utils::copyToStream($s1, $s2);
self::assertSame('foobaz', (string)$s2);
$s2 = Psr7\Utils::streamFor('');
$s1->seek(0);
Psr7\Utils::copyToStream($s1, $s2, 3);
self::assertSame('foo', (string)$s2);
Psr7\Utils::copyToStream($s1, $s2, 3);
self::assertSame('foobaz', (string)$s2);
}
public function testStopsCopyToStreamWhenWriteFails()
{
$s1 = Psr7\Utils::streamFor('foobaz');
$s2 = Psr7\Utils::streamFor('');
$s2 = FnStream::decorate($s2, [
'write' => function () {
return 0;
},
]);
Psr7\Utils::copyToStream($s1, $s2);
self::assertSame('', (string)$s2);
}
public function testStopsCopyToSteamWhenWriteFailsWithMaxLen()
{
$s1 = Psr7\Utils::streamFor('foobaz');
$s2 = Psr7\Utils::streamFor('');
$s2 = FnStream::decorate($s2, [
'write' => function () {
return 0;
},
]);
Psr7\Utils::copyToStream($s1, $s2, 10);
self::assertSame('', (string)$s2);
}
public function testCopyToStreamReadsInChunksInsteadOfAllInMemory()
{
$sizes = [];
$s1 = new Psr7\FnStream([
'eof' => function () {
return false;
},
'read' => function ($size) use (&$sizes) {
$sizes[] = $size;
return str_repeat('.', $size);
},
]);
$s2 = Psr7\Utils::streamFor('');
Psr7\Utils::copyToStream($s1, $s2, 16394);
$s2->seek(0);
self::assertSame(16394, strlen($s2->getContents()));
self::assertSame(8192, $sizes[0]);
self::assertSame(8192, $sizes[1]);
self::assertSame(10, $sizes[2]);
}
public function testStopsCopyToSteamWhenReadFailsWithMaxLen()
{
$s1 = Psr7\Utils::streamFor('foobaz');
$s1 = FnStream::decorate($s1, [
'read' => function () {
return '';
},
]);
$s2 = Psr7\Utils::streamFor('');
Psr7\Utils::copyToStream($s1, $s2, 10);
self::assertSame('', (string)$s2);
}
public function testReadsLines()
{
$s = Psr7\Utils::streamFor("foo\nbaz\nbar");
self::assertSame("foo\n", Psr7\Utils::readLine($s));
self::assertSame("baz\n", Psr7\Utils::readLine($s));
self::assertSame('bar', Psr7\Utils::readLine($s));
}
public function testReadsLinesUpToMaxLength()
{
$s = Psr7\Utils::streamFor("12345\n");
self::assertSame('123', Psr7\Utils::readLine($s, 4));
self::assertSame("45\n", Psr7\Utils::readLine($s));
}
public function testReadLinesEof()
{
// Should return empty string on EOF
$s = Psr7\Utils::streamFor("foo\nbar");
while (!$s->eof()) {
Psr7\Utils::readLine($s);
}
self::assertSame('', Psr7\Utils::readLine($s));
}
public function testReadsLineUntilFalseReturnedFromRead()
{
$s = $this->getMockBuilder('GuzzleHttp\Psr7\Stream')
->setMethods(['read', 'eof'])
->disableOriginalConstructor()
->getMock();
$s->expects(self::exactly(2))
->method('read')
->will(self::returnCallback(function () {
static $c = false;
if ($c) {
return false;
}
$c = true;
return 'h';
}));
$s->expects(self::exactly(2))
->method('eof')
->will(self::returnValue(false));
self::assertSame('h', Psr7\Utils::readLine($s));
}
public function testCalculatesHash()
{
$s = Psr7\Utils::streamFor('foobazbar');
self::assertSame(md5('foobazbar'), Psr7\Utils::hash($s, 'md5'));
}
public function testCalculatesHashThrowsWhenSeekFails()
{
$s = new NoSeekStream(Psr7\Utils::streamFor('foobazbar'));
$s->read(2);
$this->expectExceptionGuzzle('RuntimeException');
Psr7\Utils::hash($s, 'md5');
}
public function testCalculatesHashSeeksToOriginalPosition()
{
$s = Psr7\Utils::streamFor('foobazbar');
$s->seek(4);
self::assertSame(md5('foobazbar'), Psr7\Utils::hash($s, 'md5'));
self::assertSame(4, $s->tell());
}
public function testOpensFilesSuccessfully()
{
$r = Psr7\Utils::tryFopen(__FILE__, 'r');
$this->assertInternalTypeGuzzle('resource', $r);
fclose($r);
}
public function testThrowsExceptionNotWarning()
{
$this->expectExceptionGuzzle('RuntimeException', 'Unable to open "/path/to/does/not/exist" using mode "r"');
Psr7\Utils::tryFopen('/path/to/does/not/exist', 'r');
}
public function testThrowsExceptionNotValueError()
{
$this->expectExceptionGuzzle('RuntimeException', 'Unable to open "" using mode "r"');
Psr7\Utils::tryFopen('', 'r');
}
public function testCreatesUriForValue()
{
self::assertInstanceOf('GuzzleHttp\Psr7\Uri', Psr7\Utils::uriFor('/foo'));
self::assertInstanceOf(
'GuzzleHttp\Psr7\Uri',
Psr7\Utils::uriFor(new Psr7\Uri('/foo'))
);
}
public function testValidatesUri()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
Psr7\Utils::uriFor([]);
}
public function testKeepsPositionOfResource()
{
$h = fopen(__FILE__, 'r');
fseek($h, 10);
$stream = Psr7\Utils::streamFor($h);
self::assertSame(10, $stream->tell());
$stream->close();
}
public function testCreatesWithFactory()
{
$stream = Psr7\Utils::streamFor('foo');
self::assertInstanceOf('GuzzleHttp\Psr7\Stream', $stream);
self::assertSame('foo', $stream->getContents());
$stream->close();
}
public function testFactoryCreatesFromEmptyString()
{
$s = Psr7\Utils::streamFor();
self::assertInstanceOf('GuzzleHttp\Psr7\Stream', $s);
}
public function testFactoryCreatesFromNull()
{
$s = Psr7\Utils::streamFor(null);
self::assertInstanceOf('GuzzleHttp\Psr7\Stream', $s);
}
public function testFactoryCreatesFromResource()
{
$r = fopen(__FILE__, 'r');
$s = Psr7\Utils::streamFor($r);
self::assertInstanceOf('GuzzleHttp\Psr7\Stream', $s);
self::assertSame(file_get_contents(__FILE__), (string)$s);
}
public function testFactoryCreatesFromObjectWithToString()
{
$r = new HasToString();
$s = Psr7\Utils::streamFor($r);
self::assertInstanceOf('GuzzleHttp\Psr7\Stream', $s);
self::assertSame('foo', (string)$s);
}
public function testCreatePassesThrough()
{
$s = Psr7\Utils::streamFor('foo');
self::assertSame($s, Psr7\Utils::streamFor($s));
}
public function testThrowsExceptionForUnknown()
{
$this->expectExceptionGuzzle('InvalidArgumentException');
Psr7\Utils::streamFor(new \stdClass());
}
public function testReturnsCustomMetadata()
{
$s = Psr7\Utils::streamFor('foo', ['metadata' => ['hwm' => 3]]);
self::assertSame(3, $s->getMetadata('hwm'));
self::assertArrayHasKey('hwm', $s->getMetadata());
}
public function testCanSetSize()
{
$s = Psr7\Utils::streamFor('', ['size' => 10]);
self::assertSame(10, $s->getSize());
}
public function testCanCreateIteratorBasedStream()
{
$a = new \ArrayIterator(['foo', 'bar', '123']);
$p = Psr7\Utils::streamFor($a);
self::assertInstanceOf('GuzzleHttp\Psr7\PumpStream', $p);
self::assertSame('foo', $p->read(3));
self::assertFalse($p->eof());
self::assertSame('b', $p->read(1));
self::assertSame('a', $p->read(1));
self::assertSame('r12', $p->read(3));
self::assertFalse($p->eof());
self::assertSame('3', $p->getContents());
self::assertTrue($p->eof());
self::assertSame(9, $p->tell());
}
public function testConvertsRequestsToStrings()
{
$request = new Psr7\Request('PUT', 'http://foo.com/hi?123', [
'Baz' => 'bar',
'Qux' => 'ipsum',
], 'hello', '1.0');
self::assertSame(
"PUT /hi?123 HTTP/1.0\r\nHost: foo.com\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
Psr7\Message::toString($request)
);
}
public function testConvertsResponsesToStrings()
{
$response = new Psr7\Response(200, [
'Baz' => 'bar',
'Qux' => 'ipsum',
], 'hello', '1.0', 'FOO');
self::assertSame(
"HTTP/1.0 200 FOO\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello",
Psr7\Message::toString($response)
);
}
public function testCorrectlyRendersSetCookieHeadersToString()
{
$response = new Psr7\Response(200, [
'Set-Cookie' => ['bar','baz','qux']
], 'hello', '1.0', 'FOO');
self::assertSame(
"HTTP/1.0 200 FOO\r\nSet-Cookie: bar\r\nSet-Cookie: baz\r\nSet-Cookie: qux\r\n\r\nhello",
Psr7\Message::toString($response)
);
}
public function testCanModifyRequestWithUri()
{
$r1 = new Psr7\Request('GET', 'http://foo.com');
$r2 = Psr7\Utils::modifyRequest($r1, [
'uri' => new Psr7\Uri('http://www.foo.com'),
]);
self::assertSame('http://www.foo.com', (string)$r2->getUri());
self::assertSame('www.foo.com', (string)$r2->getHeaderLine('host'));
}
public function testCanModifyRequestWithUriAndPort()
{
$r1 = new Psr7\Request('GET', 'http://foo.com:8000');
$r2 = Psr7\Utils::modifyRequest($r1, [
'uri' => new Psr7\Uri('http://www.foo.com:8000'),
]);
self::assertSame('http://www.foo.com:8000', (string)$r2->getUri());
self::assertSame('www.foo.com:8000', (string)$r2->getHeaderLine('host'));
}
public function testCanModifyRequestWithCaseInsensitiveHeader()
{
$r1 = new Psr7\Request('GET', 'http://foo.com', ['User-Agent' => 'foo']);
$r2 = Psr7\Utils::modifyRequest($r1, ['set_headers' => ['User-agent' => 'bar']]);
self::assertSame('bar', $r2->getHeaderLine('User-Agent'));
self::assertSame('bar', $r2->getHeaderLine('User-agent'));
}
public function testReturnsAsIsWhenNoChanges()
{
$r1 = new Psr7\Request('GET', 'http://foo.com');
$r2 = Psr7\Utils::modifyRequest($r1, []);
self::assertInstanceOf('GuzzleHttp\Psr7\Request', $r2);
$r1 = new Psr7\ServerRequest('GET', 'http://foo.com');
$r2 = Psr7\Utils::modifyRequest($r1, []);
self::assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $r2);
}
public function testReturnsUriAsIsWhenNoChanges()
{
$r1 = new Psr7\Request('GET', 'http://foo.com');
$r2 = Psr7\Utils::modifyRequest($r1, ['set_headers' => ['foo' => 'bar']]);
self::assertNotSame($r1, $r2);
self::assertSame('bar', $r2->getHeaderLine('foo'));
}
public function testRemovesHeadersFromMessage()
{
$r1 = new Psr7\Request('GET', 'http://foo.com', ['foo' => 'bar']);
$r2 = Psr7\Utils::modifyRequest($r1, ['remove_headers' => ['foo']]);
self::assertNotSame($r1, $r2);
self::assertFalse($r2->hasHeader('foo'));
}
public function testAddsQueryToUri()
{
$r1 = new Psr7\Request('GET', 'http://foo.com');
$r2 = Psr7\Utils::modifyRequest($r1, ['query' => 'foo=bar']);
self::assertNotSame($r1, $r2);
self::assertSame('foo=bar', $r2->getUri()->getQuery());
}
public function testModifyRequestKeepInstanceOfRequest()
{
$r1 = new Psr7\Request('GET', 'http://foo.com');
$r2 = Psr7\Utils::modifyRequest($r1, ['remove_headers' => ['non-existent']]);
self::assertInstanceOf('GuzzleHttp\Psr7\Request', $r2);
$r1 = new Psr7\ServerRequest('GET', 'http://foo.com');
$r2 = Psr7\Utils::modifyRequest($r1, ['remove_headers' => ['non-existent']]);
self::assertInstanceOf('Psr\Http\Message\ServerRequestInterface', $r2);
}
public function testModifyServerRequestWithUploadedFiles()
{
$request = new Psr7\ServerRequest('GET', 'http://example.com/bla');
$file = new Psr7\UploadedFile('Test', 100, \UPLOAD_ERR_OK);
$request = $request->withUploadedFiles([$file]);
/** @var Psr7\ServerRequest $modifiedRequest */
$modifiedRequest = Psr7\Utils::modifyRequest($request, ['set_headers' => ['foo' => 'bar']]);
self::assertCount(1, $modifiedRequest->getUploadedFiles());
$files = $modifiedRequest->getUploadedFiles();
self::assertInstanceOf('GuzzleHttp\Psr7\UploadedFile', $files[0]);
}
public function testModifyServerRequestWithCookies()
{
$request = (new Psr7\ServerRequest('GET', 'http://example.com/bla'))
->withCookieParams(['name' => 'value']);
/** @var Psr7\ServerRequest $modifiedRequest */
$modifiedRequest = Psr7\Utils::modifyRequest($request, ['set_headers' => ['foo' => 'bar']]);
self::assertSame(['name' => 'value'], $modifiedRequest->getCookieParams());
}
public function testModifyServerRequestParsedBody()
{
$request = (new Psr7\ServerRequest('GET', 'http://example.com/bla'))
->withParsedBody(['name' => 'value']);
/** @var Psr7\ServerRequest $modifiedRequest */
$modifiedRequest = Psr7\Utils::modifyRequest($request, ['set_headers' => ['foo' => 'bar']]);
self::assertSame(['name' => 'value'], $modifiedRequest->getParsedBody());
}
public function testModifyServerRequestQueryParams()
{
$request = (new Psr7\ServerRequest('GET', 'http://example.com/bla'))
->withQueryParams(['name' => 'value']);
/** @var Psr7\ServerRequest $modifiedRequest */
$modifiedRequest = Psr7\Utils::modifyRequest($request, ['set_headers' => ['foo' => 'bar']]);
self::assertSame(['name' => 'value'], $modifiedRequest->getQueryParams());
}
public function testModifyServerRequestRetainsAttributes()
{
$request = (new Psr7\ServerRequest('GET', 'http://example.com/bla'))
->withAttribute('foo', 'bar');
/** @var Psr7\ServerRequest $modifiedRequest */
$modifiedRequest = Psr7\Utils::modifyRequest($request, []);
self::assertSame(['foo' => 'bar'], $modifiedRequest->getAttributes());
}
}