guzzle / psr7 Goto Github PK
View Code? Open in Web Editor NEWPSR-7 HTTP message library
License: MIT License
PSR-7 HTTP message library
License: MIT License
According to the PSR-7 spec, getPath() must always return "/".
Hi.
I write API and I use behat to test it.
I'm getting Warning: fread(): Length parameter must be greater than 0 in vendor/guzzlehttp/psr7/src/Stream.php line 211
for every response with empty body.
I made quick fix for that line like
return $length > 0 ? fread($this->stream, $length) : '';
PHP: 7.0.8
guzzlehttp/psr7: 1.3.1
I borrowed the RFC3986 tests from Guzzle, and two of them aren't passing for the resolve
method. There is also, what looks like, some code duplication in the resolve
logic, so we should take look at it's implementation.
Hi guys,
Looks like Uri implementation does not support the utf8 because of PHP parse_url function (see https://secure.php.net/manual/en/function.parse-url.php#114817). I tested it on PHP 5.5 with any utf8 encoded Uri. It corrupts some characters for some reason. Obviously this is the issue with PHP parse_url function, but still would be nice to have that support.
Thanks
Is another tag planned in the near future. It's also necessary for people using old versions of composer.
At this line https://github.com/guzzle/psr7/blob/master/src/MultipartStream.php#L145 MultipartStream::getHeader() compares part header name case-sensitively, for this reason option like
'multipart' => [..., 'headers' => [ 'Content-Type' => $customContentType ] ]
is ignored
I want override the GuzzleHttp\Psr7\Uri
class, for adds custom methods, but methods in GuzzleHttp\Psr7\Uri
use private static properties via static, and script is fail, because in my class (overidded) the property not found.
Hi,
I was going through the guzzle code, have a doubt regarding the implementation
Line 99 in 0c79977
Doesn't it need to preserve the case sensitivity? See
While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders()
and I am seeing
Line 42 in 0c79977
public function getHeaders()
{
return $this->headerLines;
}
I understand it finally is returning the preserved value. But does headerLines
in headers is a bit confusing? I wished the variable name is like
public function getHeaders()
{
return $this->headers;
}
public function getHeaderLines()
{
return $this->headerLines;
}
Thank you
I need to cache serialized Response
objects in a database, but the Stream
-based bodies are posing a challenge. Here's a unit test that demonstrates my problem:
public function testTest()
{
$original = new Response(200, [], 'body');
$serialized = serialize($original);
$unserialized = unserialize($serialized);
$this->assertEquals('body', (string) $original->getBody(), 'Got expected body value from original object.');
$this->assertEquals('body', (string) $unserialized->getBody(), 'Got expected body value from object after serializing and unserializing.');
}
$ ./vendor/bin/phpunit tests/SerializationTest.php
PHPUnit 4.8.21 by Sebastian Bergmann and contributors.
PHP Warning: fseek() expects parameter 1 to be resource, integer given in /Users/travis.carden/Projects/psr7/src/Stream.php on line 199
PHP Warning: stream_get_contents() expects parameter 1 to be resource, integer given in /Users/travis.carden/Projects/psr7/src/Stream.php on line 94
F
Warning: fseek() expects parameter 1 to be resource, integer given in /Users/travis.carden/Projects/psr7/src/Stream.php on line 199
Warning: stream_get_contents() expects parameter 1 to be resource, integer given in /Users/travis.carden/Projects/psr7/src/Stream.php on line 94
Time: 55 ms, Memory: 4.50Mb
There was 1 failure:
1) GuzzleHttp\Tests\Psr7\SerializationTest::testSerialization
Got expected body value from object after serializing and unserializing.
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'body'
+''
/Users/travis.carden/Projects/psr7/tests/SerializationTest.php:16
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
Is there any way to make responses serializable? If not, I'll probably just store a string version of the body next to the serialized Response
in my cache setter and withResponse()
it back into the unserialized Response
in my cache getter.
Hello, I hit one problem when use instance of GuzzleHttp\Psr7\Stream
.
echo $response->getBody()->getContents();
method returns me empty string, although the logger show me correct response.
The problem was that the logger use (string) $response->getBody()
and we seek to the end of stream.
Should we seek back before returns content?
public function getContents()
{
$this->rewind();
$contents = stream_get_contents($this->stream);
if ($contents === false) {
throw new \RuntimeException('Unable to read stream contents');
}
return $contents;
}
Seems __toString()
can call getContent()
.
Hello,
I am trying to work with popen streams like this:
$stream = \GuzzleHttp\Psr7\stream_for(
popen(
'ls', 'r'
)
);
But $stream->getSize()
always returns 0 which causes problems with the Slim framework (see slimphp/Slim#1838).
PSR-7 says that getSize()
should return null when the size is unknown, which seems to be the case here.
Hello, I'm running into this fatal error with one of my tests:
PHP Fatal error: Method GuzzleHttp\Psr7\Uri::__toString() must not throw an exception in /path-to/test/TestCase.php on line 0
It appears to stem from a call to GuzzleHttp\Client::getAsync(), though wrapping that call in a try/catch doesn't seem to catch an exception.
Thanks
// Message class implements the Message Interface
class Message implements MessageInterface {
//put code
}
// Server Request class is an abstract basis for the request
abstract class ServerRequest extends Message implements ServerRequestInterface {
//put code
}
// Request class inherits and provides the USER (according to PSR) access to all methods
class Request extends ServerRequest implements RequestInterface {
// put code
}
see https://github.com/KpuTuK/Neiron/tree/master/src/Neiron/Components/Http
This is my try for a function that sends header and body with stream support on the basis of a ResponseInterface:
<?php
/**
* @param ResponseInterface $response
*/
function out(ResponseInterface $response)
{
header(sprintf('%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase()));
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
stream_copy_to_stream(StreamWrapper::getResource($response->getBody()), fopen('php://output', 'w'));
}
I think this could be a nice contribution to your functions.php
. If you agree, I am going to create a PR.
I'm getting the below message when interacting with Guzzle:
[Symfony\Component\Debug\Exception\FatalErrorException]
Class GuzzleHttp\Psr7\Response contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Psr\Http\Message\ResponseInterface::setPostField)
Couldn't read incrementally from an InflateStream:
$content = fopen(__DIR__.'/InflateStreamTestData.txt.gz', 'rb');
$a = Psr7\stream_for($content);
$b = new InflateStream($a);
$this->assertEquals('Nulla voluptate qui consectetur cillum consectetur.', $b->read(51));
Is this a miss-use of the API? Or is this a bug? Missing feature?
If one of the later, please provide direction so I can work on the pull request.
Test case here: patsplat@daac696
Currently need to implement ServerRequestInterface and UploadedFileInterface
It is not issue, it is rather a question. Why not add this functionality (StreamWrapper) in the very class of the stream? These classes, in fact, are wrapper?
public function __call($name, $arguments)
{
if (false !== strpos($name, 'stream_')) {
$name = substr($name, 7);
}
$method = strtolower(str_replace('_', '', $name));
if (! method_exists($this, $method)) {
throw new InvalidArgumentException(
sprintf('Method "%s" doesn\'t exist', $name)
);
}
return call_user_func_array([$this, $method], $arguments);
}
PSR-7 has an issue. https://evertpot.com/psr-7-issues
Some people i helped abandoned Guzzle due to this bug.
Try it yourself with an 1GB file and send a partial stream.
$stream = GuzzleHttp\Stream\Stream::factory(fopen($path, 'r'));
$stream->seek($offset);
while (!$stream->eof()) {
echo $stream->read($length);
}
$stream->close();
I do need that feature of conditionally loading the global functions due to messed up autoloading on my side.
Specifically, this line https://github.com/guzzle/psr7/blob/master/src/Uri.php#L573 transforms all paths to absolute.
https://github.com/php-fig/http-message/blob/master/src/UriInterface.php#L113 and https://github.com/php-fig/http-message/blob/master/src/UriInterface.php#L249 specify that rootless relative paths MUST be supported.
When resolving a path for a base url, the combination of the guzzle package and this one results in the host not being set at all.
To explain: the buildUri method in the Guzzle Client always ensures a scheme. So if you have the following base/rel uri:
$base = new Uri('http://example.org');
$rel = new Uri('/foo'); # does not have a scheme
If you request $rel
with Guzzle, and you have middleware that uses the resolve method to make a proper uri out of the two:
# in middleware, $rel now has a scheme added by Guzzle
$uri = Uri::resolve($base, $rel);
You would expect this to yield http://example.org/foo
, yet the resolver checks for a scheme in $rel
and if so, assumes the host is set and returns the normalized $rel
without looking at the base uri:
Lines 69 to 71 in 64862e8
Which results in a uri without a host. Now I don't think it's incorrect that the scheme is added by Guzzle, which is why I create the issue in this repo instead. I think the resolve method should check for both scheme and host in the if statement I linked here above.
When opening a file with gzopen
it is possible to specify some extra options, compression level, etc
When a Stream
is created it detects readable/writable checking the mode with $readWriteHash
which doesn't have entries for all possible modes, eg 'rb9'
or wb2
.
This results in the Stream
being incorrectly marked as neither readable or writable.
I would be happy to make a pull request, but thinking about the best solution. It would be possible to add all the variations to $readWriteHash
, but maybe some string manipulation is better option.
withAddedHeader()
(difference being the usage of clone
) - bad for maintainabilitywithHeader()
, judging by the name & usagesI found an issue about \GuzzleHttp\Psr7\parse_query()
not work correct when a query string contains an array.
My english is not good, so try to use an example to explain this issue,
and please to comfirm the different behavior, thanks.
For example:
// According to https://github.com/guzzle/guzzle/blob/master/src/Client.php#L350
// Generate a query string
$query = [
'foo' => ['item1', 'item2', 'item3'],
];
$queryString = http_build_query($query, null, '&', PHP_QUERY_RFC3986);
// Parse the query string by PHP build-in parse_str()
// @see http://php.net/manual/en/function.parse-str.php
$parseStrResult = [];
parse_str($queryString, $parseStrResult);
// Show the different between parse_str() and parse_query()
$queries = [
'query_string' => $queryString,
'origin_query' => $originQuery,
'parse_str' => $parseStrResult,
'parse_query' => \GuzzleHttp\Psr7\parse_query($queryString),
'parse_query_with_rfc3986' => \GuzzleHttp\Psr7\parse_query($queryString, PHP_QUERY_RFC3986),
'parse_query_with_rfc1738' => \GuzzleHttp\Psr7\parse_query($queryString, PHP_QUERY_RFC1738),
];
print_r($queries);
the output:
Array [12/21256]
(
[query_string] => foo%5B0%5D=item1&foo%5B1%5D=item2&foo%5B2%5D=item3
[origin_query] => Array
(
[foo] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
)
[parse_str] => Array
(
[foo] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
)
[parse_query] => Array
(
[foo[0]] => item1
[foo[1]] => item2
[foo[2]] => item3
)
[parse_query_with_rfc3986] => Array
(
[foo[0]] => item1
[foo[1]] => item2
[foo[2]] => item3
)
[parse_query_with_rfc1738] => Array
(
[foo[0]] => item1
[foo[1]] => item2
[foo[2]] => item3
)
)
There are no odt, ods and etc extensions. Can you add them? Thanks =)
https://www.openoffice.org/framework/documentation/mimetypes/mimetypes.html
Request overrides the withHeader
method declared in MessageTrait
, so the original one is aliased to withParentHeader
.
Shouldn't it be protected or private?
The function copy_to_stream() should return the count of copied bytes. Like the PHP function stream_copy_to_stream() does.
Current workaround is to use copy_to_string() and check the length of the returned string but this does not play well for large amounts of data.
Hi,
I stumbled upon this today
Example code
$uri = new Uri('http://user:[email protected]');
$uri = Uri::resolve($uri, '/path');
echo $uri;
Expected:
http://user:[email protected]/path
Actual:
http://example.com/path
ServerRequestInterface and UploadedFileInterface have been added. So the README part "Not Implemented" can be removed.
In RFC3986 section 3, a valid absolute URI which contains no authority can be written like this: urn:example:animal:ferret:nose
. In this case, the URI scheme is urn
, and the path is example:animal:ferret:nose
:
var_dump(parse_url('urn:example:animal:ferret:nose'));
array(2) {
["scheme"]=>
string(3) "urn"
["path"]=>
string(26) "example:animal:ferret:nose"
}
Problem
The Uri::createUriString
function appends //
to ANY scheme, when it should only be appending if the authority exists. As a result, the string becomes urn:///example:animal:ferret:nose
Solution
Before appending //
, ensure $authority
is not empty. Before prepending /
to $path
, ensure $authority
is not empty.
According to https://github.com/guzzle/psr7/blob/master/src/Request.php#L28-L29 the Request
class can be created using
<?php
$request = new Request(null, null);
However, the UriInterface validation will cause that to throw an InvalidArgumentException
. See https://github.com/guzzle/psr7/blob/master/src/Request.php#L43-L49
Looking at the PSR-7 definition for RequestInterface
, neither getMethod
or getUri
may return anything but a string
and UriInterface
respectively. My gut feeling is that the documentation should then be considered invalid.
I know that it's super obsolete, but some of our customers still use it...
It would be great if Guzzle PSR-7 implementation will also be 5.3 compatible.
I was wondering why parse_request doesn't support absolute URI's. Request like this fail:
GET https://www.google.com HTTP/1.1
The regex explicity requires a starting slash after the keyword:
if (!preg_match('/^[a-zA-Z]+\s+\/.*/', $data['start-line'])) {
throw new \InvalidArgumentException('Invalid request string');
}
Are there any objections to support absolute URI's as well? I'm trying to build a php proxy server using reactphp/http (which uses guzzle/psr7) and it doesn't work because of this. If no objections I can create a PR.
Best,
Nicolas
Hey,
Any particular reason why stream_for
function does not accept an integer ?
It throws that exception when using a parameter like:
[
'name' => 'event',
'contents' => '1'
]
php > echo (new \GuzzleHttp\Psr7\Uri('//bar'))->__toString();
bar:
php > echo (new \GuzzleHttp\Psr7\Uri())->withHost('bar')->getAuthority();
bar:
The condition to check if we got to the end of the line in readline
is defined as:
if ($byte == PHP_EOL || ++$size == $maxLength - 1) {
// ...
It will work properly if the stream was generated by a server, which uses the same type of line endings as the system on which the stream is being processed.
For example: an application running on a Linux server returns a stream using \n
as EOL. readline
is used to read this stream on a Windows server, where PHP_EOL === "\r\n"
. Because $byte == "\r\n"
will never be true, readline
will read the whole stream (or to $maxLength
, if provided) instead of only the first line.
SeverRequest::fromGlobals
only works on Apache as getallheaders
does not exist on other webservers as @iotch pointed out in #54 (comment) and I can confirm. So the headers are not available then.
We can provide a fallback solution reading the headers from $_SERVER
(in an ugly way). This is also done in symfony etc. Maybe it's a good idea to implement getallheaders
as Polyfill and add it to https://github.com/symfony/polyfill
When using relative URIs they are sent to the Uri constructor and parse_url
is called to extract information from them.
Conditions:
If the path contains a colon.
...and what comes after the colon character must be numeric.
...and number of numeric characters after the colon is < 6.
...in other words if it "kinda looks like a port number"...
...and there are no query parameters.
...and there is no fragment.
...and there are no previous occurrences of the colon sign.
...then parse_url
will fail to recognize the path component and return false
// Psr\Http\Message\UriInterface\Uri
public function __construct($uri = '')
{
if ($uri != null) {
$parts = parse_url($uri);
....
}
...
public static function resolve(UriInterface $base, $rel)
{
...
if (!($rel instanceof UriInterface)) {
$rel = new self($rel);
}
....
}
You can reproduce the issue via:
$client = new GuzzleHttp\Client(['base_uri' => 'http://example.com:90/']);
$client->request('get', '/a/b/c/d/e:12345');
I'm using dropbox-sdk to upload files to the dropbox storage. This lib uses CURLOPT_INFILE
curl option with resource as value to send file.
https://github.com/dropbox/dropbox-sdk-php/blob/master/lib/Dropbox/Client.php#L291
It assumes that StreamWrapper::stream_cast()
must be implemented.
I decided extend \GuzzleHttp\Psr7\StreamWrapper
class to add stream_cast()
method but I found that I can't get stream resource which should return stream_cast()
.
I created such hack, but I'm not really happy with it:
public function stream_cast($cast_as)
{
$clonedStream = clone($this->stream);
return $clonedStream->detach();
}
What do you think about implementation of StreamWrapper::stream_cast()
method?
Commit 45054d9#diff-f89246dce7e387482b2c6c584a5e7e9dR97 have introduced a bug by comparing $body
with empty string.
I did not dug too deeply to find out the real reason of wrong behavior, but I guess it is caused by implicit calling of GuzzleHttp\Psr7\Stream::__toString()
in order to cast object to string to make a comparison.
$client = new \GuzzleHttp\Client(['base_uri' => 'https://google.com.ua/']);
$response = $client->request('GET');
$html = $response->getBody()->getContents();
$html
contains a response HTML
$html
is an empty string
Rolling back that line to if ($body !== null)
fixes the problem. Not sure whether it is a proper fix.
PHP 5.6.20
Ubuntu 16.04
guzzle/psr7@dev-master
This library is being included by Google Cloud API and I am getting errors about there being no CA Cert. Fair enough.
However, I have no idea where I can set the location of the certificate, or how to state that I don't want ot use one.
I've had to kludge the library and set all CA Cert settings to false
- obviously no the best idea.
a composer update broke our use of guzzlehttp, when updating to psr7 1.3.1
forcing our composer.json file to install 1.3.0 got it working for us again.
the exception thrown is:
"cURL error 3: malformed (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)"
the url is like http://10.10.20.20:2080/api/cars/1
edit: broken with commit 889f21e
https://github.com/guzzle/psr7/blob/master/tests/LimitStreamTest.php#L52
I don't know if it is a real issue, but do you know, that this test passes only because Psr7\stream_for()
creates 'php://temp'
stream? Php tries to fseek()
to non-existing offset and gets an error there https://github.com/guzzle/psr7/blob/master/src/Stream.php#L200.
But if Psr7\stream_for()
called fopen('<path to some file>', 'w');
, the test would fail, because
In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0.
https://php.net/manual/en/function.fseek.php
$stream = fopen('php://temp', 'r+');
echo fseek($stream, 10) . "\n"; <— -1
$stream = fopen('./fseek.file', 'w');
echo fseek($stream, 10) . "\n"; <— 0
I discovered this, when I tested PSR-7 on HHVM. In HHVM fseek()
can go beyond the end-of-line in 'php://temp'
streams too, so this test fails. And now I don't know who's problem it is, and is it a problem at all.
Tested on Ubuntu 14.04, php 5.5.26, hhvm 3.9.1
I have this code
$data = array( 'File-Name' => $file_name, 'Mime-Type' => 'application/pdf', 'File' => $sourcePath ); $multipartStream = new MultipartStream($data);
but I'm getting an error of
Catchable fatal error: Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string given, called in /Applications/MAMP/htdocs/adobesignwp/wp-content/plugins/Gravity2PDF/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php on line 70 and defined in /Applications/MAMP/htdocs/adobesignwp/wp-content/plugins/Gravity2PDF/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php on line 79
When doing the following, I'd expect it to return 80.
$uri = new Uri('http://example.com/foo/bar');
return $uri->getPort();
Or if not then I should very much expect it when doing this.
$uri = new Uri('http://example.com/foo/bar');
return $uri->withPort(80)->getPort();
Hello guys,
I want to serialize requests and responses as well.
I found the solution on #53 - but
The \GuzzleHttp\Psr7\str
function does a good job indeed, except it doesn't make a difference between HTTP and HTTPS.
<?php
use GuzzleHttp\Psr7\Request;
use function \GuzzleHttp\Psr7\str;
require_once __DIR__ . '/../vendor/autoload.php';
$secureRequest = new Request('GET', 'https://example.org');
$unsecureRequest = new Request('GET', 'http://example.org');
var_dump(str($secureRequest) === str($unsecureRequest)); // true
This is quite disturbing because when I store a request as string for further use, the request automatically switches to HTTP...
Any ideas?
Thanks,
Ben
Something has changed between PHP 7 and PHP 5 in terms of handling fopen resources in multipart transfers via GuzzleHttpClient. Files need to be proxied via local file first otherwise requests seem to be different between php versions.
Looks like an invalid chunked body problem
If I use the function str(MessageInterface $message) I have to manually rewind the body of the message.
I am just wondering. Is this the desirable behaviour? I was expecting that it would automatically rewind the message body.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.