repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Host.php | src/Header/Host.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header;
/**
* @throws Exception\InvalidArgumentException
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23
*/
class Host implements HeaderInterface
{
/**
* @var string
*/
protected $value;
public static function fromString($headerLine)
{
list($name, $value) = GenericHeader::splitHeaderLine($headerLine);
// check to ensure proper header type for this factory
if (strtolower($name) !== 'host') {
throw new Exception\InvalidArgumentException('Invalid header line for Host string: "' . $name . '"');
}
// @todo implementation details
return new static($value);
}
public function __construct($value = null)
{
if ($value !== null) {
HeaderValue::assertValid($value);
$this->value = $value;
}
}
public function getFieldName()
{
return 'Host';
}
public function getFieldValue()
{
return (string) $this->value;
}
public function toString()
{
return 'Host: ' . $this->getFieldValue();
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentRange.php | src/Header/ContentRange.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header;
/**
* @throws Exception\InvalidArgumentException
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16
*/
class ContentRange implements HeaderInterface
{
/**
* @var string
*/
protected $value;
public static function fromString($headerLine)
{
list($name, $value) = GenericHeader::splitHeaderLine($headerLine);
// check to ensure proper header type for this factory
if (strtolower($name) !== 'content-range') {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid header line for Content-Range string: "%s"',
$name
));
}
// @todo implementation details
return new static($value);
}
public function __construct($value = null)
{
if ($value !== null) {
HeaderValue::assertValid($value);
$this->value = $value;
}
}
public function getFieldName()
{
return 'Content-Range';
}
public function getFieldValue()
{
return (string) $this->value;
}
public function toString()
{
return 'Content-Range: ' . $this->getFieldValue();
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Allow.php | src/Header/Allow.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header;
use Zend\Http\Request;
/**
* Allow Header
*
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7
*/
class Allow implements HeaderInterface
{
/**
* List of request methods
* true states that method is allowed, false - disallowed
* By default GET and POST are allowed
*
* @var array
*/
protected $methods = [
Request::METHOD_OPTIONS => false,
Request::METHOD_GET => true,
Request::METHOD_HEAD => false,
Request::METHOD_POST => true,
Request::METHOD_PUT => false,
Request::METHOD_DELETE => false,
Request::METHOD_TRACE => false,
Request::METHOD_CONNECT => false,
Request::METHOD_PATCH => false,
];
/**
* Create Allow header from header line
*
* @param string $headerLine
* @return static
* @throws Exception\InvalidArgumentException
*/
public static function fromString($headerLine)
{
list($name, $value) = GenericHeader::splitHeaderLine($headerLine);
// check to ensure proper header type for this factory
if (strtolower($name) !== 'allow') {
throw new Exception\InvalidArgumentException('Invalid header line for Allow string: "' . $name . '"');
}
$header = new static();
$header->disallowMethods(array_keys($header->getAllMethods()));
$header->allowMethods(explode(',', $value));
return $header;
}
/**
* Get header name
*
* @return string
*/
public function getFieldName()
{
return 'Allow';
}
/**
* Get comma-separated list of allowed methods
*
* @return string
*/
public function getFieldValue()
{
return implode(', ', array_keys($this->methods, true, true));
}
/**
* Get list of all defined methods
*
* @return array
*/
public function getAllMethods()
{
return $this->methods;
}
/**
* Get list of allowed methods
*
* @return array
*/
public function getAllowedMethods()
{
return array_keys($this->methods, true, true);
}
/**
* Allow methods or list of methods
*
* @param array|string $allowedMethods
* @return $this
*/
public function allowMethods($allowedMethods)
{
foreach ((array) $allowedMethods as $method) {
$method = trim(strtoupper($method));
if (preg_match('/\s/', $method)) {
throw new Exception\InvalidArgumentException(sprintf(
'Unable to whitelist method; "%s" is not a valid method',
$method
));
}
$this->methods[$method] = true;
}
return $this;
}
/**
* Disallow methods or list of methods
*
* @param array|string $disallowedMethods
* @return $this
*/
public function disallowMethods($disallowedMethods)
{
foreach ((array) $disallowedMethods as $method) {
$method = trim(strtoupper($method));
if (preg_match('/\s/', $method)) {
throw new Exception\InvalidArgumentException(sprintf(
'Unable to blacklist method; "%s" is not a valid method',
$method
));
}
$this->methods[$method] = false;
}
return $this;
}
/**
* Convenience alias for @see disallowMethods()
*
* @param array|string $disallowedMethods
* @return $this
*/
public function denyMethods($disallowedMethods)
{
return $this->disallowMethods($disallowedMethods);
}
/**
* Check whether method is allowed
*
* @param string $method
* @return bool
*/
public function isAllowedMethod($method)
{
$method = trim(strtoupper($method));
// disallow unknown method
if (! isset($this->methods[$method])) {
$this->methods[$method] = false;
}
return $this->methods[$method];
}
/**
* Return header as string
*
* @return string
*/
public function toString()
{
return 'Allow: ' . $this->getFieldValue();
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/ContentLocation.php | src/Header/ContentLocation.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header;
/**
* Content-Location Header
*
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.14
*/
class ContentLocation extends AbstractLocation
{
/**
* Return header name
*
* @return string
*/
public function getFieldName()
{
return 'Content-Location';
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Exception/ExceptionInterface.php | src/Header/Exception/ExceptionInterface.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Exception;
use Zend\Http\Exception\ExceptionInterface as HttpException;
interface ExceptionInterface extends HttpException
{
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Exception/RuntimeException.php | src/Header/Exception/RuntimeException.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Exception;
use Zend\Http\Exception;
class RuntimeException extends Exception\RuntimeException implements
ExceptionInterface
{
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Exception/InvalidArgumentException.php | src/Header/Exception/InvalidArgumentException.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Exception;
use Zend\Http\Exception;
class InvalidArgumentException extends Exception\InvalidArgumentException implements
ExceptionInterface
{
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Exception/DomainException.php | src/Header/Exception/DomainException.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Exception;
class DomainException extends \DomainException implements ExceptionInterface
{
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Accept/FieldValuePart/EncodingFieldValuePart.php | src/Header/Accept/FieldValuePart/EncodingFieldValuePart.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Accept\FieldValuePart;
/**
* Field Value Part
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
*/
class EncodingFieldValuePart extends AbstractFieldValuePart
{
/**
* @return string
*/
public function getEncoding()
{
return $this->getInternalValues()->type;
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Accept/FieldValuePart/LanguageFieldValuePart.php | src/Header/Accept/FieldValuePart/LanguageFieldValuePart.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Accept\FieldValuePart;
/**
* Field Value Part
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
*/
class LanguageFieldValuePart extends AbstractFieldValuePart
{
public function getLanguage()
{
return $this->getInternalValues()->typeString;
}
public function getPrimaryTag()
{
return $this->getInternalValues()->type;
}
public function getSubTag()
{
return $this->getInternalValues()->subtype;
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Accept/FieldValuePart/AcceptFieldValuePart.php | src/Header/Accept/FieldValuePart/AcceptFieldValuePart.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Accept\FieldValuePart;
/**
* Field Value Part
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
*/
class AcceptFieldValuePart extends AbstractFieldValuePart
{
/**
* @return string
*/
public function getSubtype()
{
return $this->getInternalValues()->subtype;
}
/**
* @return string
*/
public function getSubtypeRaw()
{
return $this->getInternalValues()->subtypeRaw;
}
/**
* @return string
*/
public function getFormat()
{
return $this->getInternalValues()->format;
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Accept/FieldValuePart/AbstractFieldValuePart.php | src/Header/Accept/FieldValuePart/AbstractFieldValuePart.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Accept\FieldValuePart;
/**
* Field Value Part
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
*/
abstract class AbstractFieldValuePart
{
/**
* Internal object used for value retrieval
* @var object
*/
private $internalValues;
/**
* A Field Value Part this Field Value Part matched against.
* @var AbstractFieldValuePart
*/
protected $matchedAgainst;
/**
* @param object $internalValues
*/
public function __construct($internalValues)
{
$this->internalValues = $internalValues;
}
/**
* Set a Field Value Part this Field Value Part matched against.
*
* @param AbstractFieldValuePart $matchedAgainst
* @return $this
*/
public function setMatchedAgainst(AbstractFieldValuePart $matchedAgainst)
{
$this->matchedAgainst = $matchedAgainst;
return $this;
}
/**
* Get a Field Value Part this Field Value Part matched against.
*
* @return AbstractFieldValuePart|null
*/
public function getMatchedAgainst()
{
return $this->matchedAgainst;
}
/**
* @return object
*/
protected function getInternalValues()
{
return $this->internalValues;
}
/**
* @return string $typeString
*/
public function getTypeString()
{
return $this->getInternalValues()->typeString;
}
/**
* @return float $priority
*/
public function getPriority()
{
return (float) $this->getInternalValues()->priority;
}
/**
* @return \stdClass $params
*/
public function getParams()
{
return (object) $this->getInternalValues()->params;
}
/**
* @return string $raw
*/
public function getRaw()
{
return $this->getInternalValues()->raw;
}
/**
* @param mixed $key
* @return mixed
*/
public function __get($key)
{
return $this->getInternalValues()->$key;
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/src/Header/Accept/FieldValuePart/CharsetFieldValuePart.php | src/Header/Accept/FieldValuePart/CharsetFieldValuePart.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Header\Accept\FieldValuePart;
/**
* Field Value Part
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
*/
class CharsetFieldValuePart extends AbstractFieldValuePart
{
/**
* @return string
*/
public function getCharset()
{
return $this->getInternalValues()->type;
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/HeadersTest.php | test/HeadersTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http;
use ArrayIterator;
use Countable;
use Iterator;
use PHPUnit\Framework\TestCase;
use Zend\Http\Exception\InvalidArgumentException;
use Zend\Http\Exception\RuntimeException;
use Zend\Http\Header;
use Zend\Http\Header\GenericHeader;
use Zend\Http\Header\GenericMultiHeader;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\HeaderLoader;
use Zend\Http\Headers;
class HeadersTest extends TestCase
{
public function testHeadersImplementsProperClasses()
{
$headers = new Headers();
$this->assertInstanceOf(Iterator::class, $headers);
$this->assertInstanceOf(Countable::class, $headers);
}
public function testHeadersCanGetPluginClassLoader()
{
$headers = new Headers();
$this->assertInstanceOf(HeaderLoader::class, $headers->getPluginClassLoader());
}
public function testHeadersFromStringFactoryCreatesSingleObject()
{
$headers = Headers::fromString('Fake: foo-bar');
$this->assertEquals(1, $headers->count());
$header = $headers->get('fake');
$this->assertInstanceOf(GenericHeader::class, $header);
$this->assertEquals('Fake', $header->getFieldName());
$this->assertEquals('foo-bar', $header->getFieldValue());
}
public function testHeadersFromStringFactoryCreatesSingleObjectWithHeaderBreakLine()
{
$headers = Headers::fromString("Fake: foo-bar\r\n\r\n");
$this->assertEquals(1, $headers->count());
$header = $headers->get('fake');
$this->assertInstanceOf(GenericHeader::class, $header);
$this->assertEquals('Fake', $header->getFieldName());
$this->assertEquals('foo-bar', $header->getFieldValue());
}
public function testHeadersFromStringFactoryCreatesSingleObjectWithHeaderFolding()
{
$headers = Headers::fromString("Fake: foo\r\n -bar");
$this->assertEquals(1, $headers->count());
$header = $headers->get('fake');
$this->assertInstanceOf(GenericHeader::class, $header);
$this->assertEquals('Fake', $header->getFieldName());
$this->assertEquals('foo-bar', $header->getFieldValue());
}
public function testHeadersFromStringFactoryThrowsExceptionOnMalformedHeaderLine()
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('does not match');
Headers::fromString("Fake = foo-bar\r\n\r\n");
}
public function testHeadersFromStringFactoryCreatesMultipleObjects()
{
$headers = Headers::fromString("Fake: foo-bar\r\nAnother-Fake: boo-baz");
$this->assertEquals(2, $headers->count());
$header = $headers->get('fake');
$this->assertInstanceOf(GenericHeader::class, $header);
$this->assertEquals('Fake', $header->getFieldName());
$this->assertEquals('foo-bar', $header->getFieldValue());
$this->assertFalse($headers->get('anotherfake'));
$header = $headers->get('another-fake');
$this->assertInstanceOf(GenericHeader::class, $header);
$this->assertEquals('Another-Fake', $header->getFieldName());
$this->assertEquals('boo-baz', $header->getFieldValue());
$this->assertSame($header, $headers->get('another fake'));
$this->assertSame($header, $headers->get('another_fake'));
$this->assertSame($header, $headers->get('another.fake'));
}
public function testHeadersFromStringMultiHeaderWillAggregateLazyLoadedHeaders()
{
$headers = new Headers();
$pcl = $headers->getPluginClassLoader();
$pcl->registerPlugin('foo', GenericMultiHeader::class);
$headers->addHeaderLine('foo: bar1,bar2,bar3');
$headers->forceLoading();
$this->assertEquals(3, $headers->count());
}
public function testHeadersHasAndGetWorkProperly()
{
$headers = new Headers();
$headers->addHeaders([
$f = new Header\GenericHeader('Foo', 'bar'),
new Header\GenericHeader('Baz', 'baz'),
]);
$this->assertFalse($headers->has('foobar'));
$this->assertTrue($headers->has('foo'));
$this->assertTrue($headers->has('Foo'));
$this->assertSame($f, $headers->get('foo'));
}
public function testHeadersGetReturnsLastAddedHeaderValue()
{
$headers = new Headers();
$headers->addHeaders([
new Header\GenericHeader('Foo', 'bar'),
]);
$headers->addHeader(new Header\GenericHeader('Foo', $value = 'baz'));
$this->assertEquals($value, $headers->get('foo')->getFieldValue());
}
public function testHeadersAggregatesHeaderObjects()
{
$fakeHeader = new Header\GenericHeader('Fake', 'bar');
$headers = new Headers();
$headers->addHeader($fakeHeader);
$this->assertEquals(1, $headers->count());
$this->assertSame($fakeHeader, $headers->get('Fake'));
}
public function testHeadersAggregatesHeaderThroughAddHeader()
{
$headers = new Headers();
$headers->addHeader(new Header\GenericHeader('Fake', 'bar'));
$this->assertEquals(1, $headers->count());
$this->assertInstanceOf(GenericHeader::class, $headers->get('Fake'));
}
public function testHeadersAggregatesHeaderThroughAddHeaderLine()
{
$headers = new Headers();
$headers->addHeaderLine('Fake', 'bar');
$this->assertEquals(1, $headers->count());
$this->assertInstanceOf(GenericHeader::class, $headers->get('Fake'));
}
public function testHeadersAddHeaderLineThrowsExceptionOnMissingFieldValue()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('without a field');
$headers = new Headers();
$headers->addHeaderLine('Foo');
}
public function testHeadersAggregatesHeadersThroughAddHeaders()
{
$headers = new Headers();
$headers->addHeaders([new Header\GenericHeader('Foo', 'bar'), new Header\GenericHeader('Baz', 'baz')]);
$this->assertEquals(2, $headers->count());
$this->assertInstanceOf(GenericHeader::class, $headers->get('Foo'));
$this->assertEquals('bar', $headers->get('foo')->getFieldValue());
$this->assertEquals('baz', $headers->get('baz')->getFieldValue());
$headers = new Headers();
$headers->addHeaders(['Foo: bar', 'Baz: baz']);
$this->assertEquals(2, $headers->count());
$this->assertInstanceOf(GenericHeader::class, $headers->get('Foo'));
$this->assertEquals('bar', $headers->get('foo')->getFieldValue());
$this->assertEquals('baz', $headers->get('baz')->getFieldValue());
$headers = new Headers();
$headers->addHeaders([['Foo' => 'bar'], ['Baz' => 'baz']]);
$this->assertEquals(2, $headers->count());
$this->assertInstanceOf(GenericHeader::class, $headers->get('Foo'));
$this->assertEquals('bar', $headers->get('foo')->getFieldValue());
$this->assertEquals('baz', $headers->get('baz')->getFieldValue());
$headers = new Headers();
$headers->addHeaders([['Foo', 'bar'], ['Baz', 'baz']]);
$this->assertEquals(2, $headers->count());
$this->assertInstanceOf(GenericHeader::class, $headers->get('Foo'));
$this->assertEquals('bar', $headers->get('foo')->getFieldValue());
$this->assertEquals('baz', $headers->get('baz')->getFieldValue());
$headers = new Headers();
$headers->addHeaders(['Foo' => 'bar', 'Baz' => 'baz']);
$this->assertEquals(2, $headers->count());
$this->assertInstanceOf(GenericHeader::class, $headers->get('Foo'));
$this->assertEquals('bar', $headers->get('foo')->getFieldValue());
$this->assertEquals('baz', $headers->get('baz')->getFieldValue());
}
public function testHeadersAddHeadersThrowsExceptionOnInvalidArguments()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected array or Trav');
$headers = new Headers();
$headers->addHeaders('foo');
}
public function testHeadersCanRemoveHeader()
{
$headers = new Headers();
$headers->addHeaders(['Foo' => 'bar', 'Baz' => 'baz']);
$header = $headers->get('foo');
$this->assertEquals(2, $headers->count());
$headers->removeHeader($header);
$this->assertEquals(1, $headers->count());
$this->assertFalse($headers->get('foo'));
}
public function testHeadersCanClearAllHeaders()
{
$headers = new Headers();
$headers->addHeaders(['Foo' => 'bar', 'Baz' => 'baz']);
$this->assertEquals(2, $headers->count());
$headers->clearHeaders();
$this->assertEquals(0, $headers->count());
}
public function testHeadersCanBeIterated()
{
$headers = new Headers();
$headers->addHeaders(['Foo' => 'bar', 'Baz' => 'baz']);
$iterations = 0;
/** @var HeaderInterface $header */
foreach ($headers as $index => $header) {
$iterations++;
$this->assertInstanceOf(GenericHeader::class, $header);
switch ($index) {
case 0:
$this->assertEquals('bar', $header->getFieldValue());
break;
case 1:
$this->assertEquals('baz', $header->getFieldValue());
break;
default:
$this->fail('Invalid index returned from iterator');
}
}
$this->assertEquals(2, $iterations);
}
public function testHeadersCanBeCastToString()
{
$headers = new Headers();
$headers->addHeaders(['Foo' => 'bar', 'Baz' => 'baz']);
$this->assertEquals('Foo: bar' . "\r\n" . 'Baz: baz' . "\r\n", $headers->toString());
}
public function testHeadersCanBeCastToArray()
{
$headers = new Headers();
$headers->addHeaders(['Foo' => 'bar', 'Baz' => 'baz']);
$this->assertEquals(['Foo' => 'bar', 'Baz' => 'baz'], $headers->toArray());
}
public function testCastingToArrayReturnsMultiHeadersAsArrays()
{
$headers = new Headers();
$cookie1 = new Header\SetCookie('foo', 'bar');
$cookie2 = new Header\SetCookie('bar', 'baz');
$headers->addHeader($cookie1);
$headers->addHeader($cookie2);
$array = $headers->toArray();
$expected = [
'Set-Cookie' => [
$cookie1->getFieldValue(),
$cookie2->getFieldValue(),
],
];
$this->assertEquals($expected, $array);
}
public function testCastingToStringReturnsAllMultiHeaderValues()
{
$headers = new Headers();
$cookie1 = new Header\SetCookie('foo', 'bar');
$cookie2 = new Header\SetCookie('bar', 'baz');
$headers->addHeader($cookie1);
$headers->addHeader($cookie2);
$string = $headers->toString();
$expected = [
'Set-Cookie: ' . $cookie1->getFieldValue(),
'Set-Cookie: ' . $cookie2->getFieldValue(),
];
$expected = implode("\r\n", $expected) . "\r\n";
$this->assertEquals($expected, $string);
}
public function testZeroIsAValidHeaderValue()
{
$headers = Headers::fromString('Fake: 0');
$this->assertSame('0', $headers->get('Fake')->getFieldValue());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testCRLFAttack()
{
$this->expectException(RuntimeException::class);
Headers::fromString("Fake: foo-bar\r\n\r\nevilContent");
}
public function testAddHeaderLineMultipleHeadersGet()
{
$headers = new Headers();
$headers->addHeaderLine('Set-Cookie: cookie1=value1');
$headers->addHeaderLine('Set-Cookie', 'cookie2=value2');
$result = $headers->get('Set-Cookie');
self::assertInstanceOf(ArrayIterator::class, $result);
self::assertCount(2, $result);
self::assertContainsOnlyInstancesOf(Header\SetCookie::class, $result);
}
public function testAddHeaderLineMultipleHeadersToString()
{
$headers = new Headers();
$headers->addHeaderLine('Set-Cookie: cookie1=value1');
$headers->addHeaderLine('Set-Cookie', 'cookie2=value2');
self::assertSame(
'Set-Cookie: cookie1=value1' . "\r\n"
. 'Set-Cookie: cookie2=value2' . "\r\n",
$headers->toString()
);
}
public function testAddHeaderMultipleHeadersGet()
{
$headers = new Headers();
$headers->addHeader(new Header\SetCookie('cookie1', 'value1'));
$headers->addHeader(new Header\SetCookie('cookie2', 'value2'));
$result = $headers->get('Set-Cookie');
self::assertInstanceOf(ArrayIterator::class, $result);
self::assertCount(2, $result);
self::assertContainsOnlyInstancesOf(Header\SetCookie::class, $result);
}
public function testAddHeaderMultipleHeadersToString()
{
$headers = new Headers();
$headers->addHeader(new Header\SetCookie('cookie1', 'value1'));
$headers->addHeader(new Header\SetCookie('cookie2', 'value2'));
self::assertSame(
'Set-Cookie: cookie1=value1' . "\r\n"
. 'Set-Cookie: cookie2=value2' . "\r\n",
$headers->toString()
);
}
public function testAddHeadersMultipleHeadersGet()
{
$headers = new Headers();
$headers->addHeaders([
new Header\SetCookie('cookie1', 'value1'),
['Set-Cookie', 'cookie2=value2'],
['Set-Cookie' => 'cookie3=value3'],
'Set-Cookie: cookie4=value4',
'Set-Cookie' => 'cookie5=value5',
]);
$result = $headers->get('Set-Cookie');
self::assertInstanceOf(ArrayIterator::class, $result);
self::assertCount(5, $result);
self::assertContainsOnlyInstancesOf(Header\SetCookie::class, $result);
}
public function testAddHeadersMultipleHeadersToString()
{
$headers = new Headers();
$headers->addHeaders([
new Header\SetCookie('cookie1', 'value1'),
['Set-Cookie', 'cookie2=value2'],
['Set-Cookie' => 'cookie3=value3'],
'Set-Cookie: cookie4=value4',
'Set-Cookie' => 'cookie5=value5',
]);
self::assertSame(
'Set-Cookie: cookie1=value1' . "\r\n"
. 'Set-Cookie: cookie2=value2' . "\r\n"
. 'Set-Cookie: cookie3=value3' . "\r\n"
. 'Set-Cookie: cookie4=value4' . "\r\n"
. 'Set-Cookie: cookie5=value5' . "\r\n",
$headers->toString()
);
}
public function testFromStringMultipleHeadersGet()
{
$headers = Headers::fromString(
'Set-Cookie: cookie1=value1' . "\r\n"
. 'Set-Cookie: cookie2=value2'
);
$result = $headers->get('Set-Cookie');
self::assertInstanceOf(ArrayIterator::class, $result);
self::assertCount(2, $result);
self::assertContainsOnlyInstancesOf(Header\SetCookie::class, $result);
}
public function testFromStringHeadersToString()
{
$headers = Headers::fromString(
'Set-Cookie: cookie1=value1' . "\r\n"
. 'Set-Cookie: cookie2=value2'
);
self::assertSame(
'Set-Cookie: cookie1=value1' . "\r\n"
. 'Set-Cookie: cookie2=value2' . "\r\n",
$headers->toString()
);
}
public function testThrowExceptionOnInvalidHeader()
{
$headers = new Headers();
$headers->addHeaderLine('Location', "/mail\r\ntest");
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid header value detected');
$headers->get('Location');
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/ClientTest.php | test/ClientTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http;
use ArrayIterator;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;
use Zend\Http\Client;
use Zend\Http\Client\Adapter\AdapterInterface;
use Zend\Http\Client\Adapter\Curl;
use Zend\Http\Client\Adapter\Proxy;
use Zend\Http\Client\Adapter\Socket;
use Zend\Http\Client\Adapter\Test;
use Zend\Http\Client\Exception as ClientException;
use Zend\Http\Cookies;
use Zend\Http\Exception as HttpException;
use Zend\Http\Header\AcceptEncoding;
use Zend\Http\Header\SetCookie;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Uri\Http;
use ZendTest\Http\TestAsset\ExtendedClient;
class ClientTest extends TestCase
{
public function testIfCookiesAreSticky()
{
$initialCookies = [
new SetCookie('foo', 'far', null, '/', 'www.domain.com'),
new SetCookie('bar', 'biz', null, '/', 'www.domain.com'),
];
$requestString = 'GET http://www.domain.com/index.php HTTP/1.1' . "\r\n"
. 'Host: domain.com' . "\r\n"
. 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) Gecko/20100101 Firefox/16.0' . "\r\n"
. 'Accept: */*' . "\r\n"
. 'Accept-Language: en-US,en;q=0.5' . "\r\n"
. 'Accept-Encoding: gzip, deflate' . "\r\n"
. 'Connection: keep-alive' . "\r\n";
$request = Request::fromString($requestString);
$client = new Client('http://www.domain.com/');
$client->setRequest($request);
$client->addCookie($initialCookies);
$cookies = new Cookies($client->getRequest()->getHeaders());
$rawHeaders = 'HTTP/1.1 200 OK' . "\r\n"
. 'Access-Control-Allow-Origin: *' . "\r\n"
. 'Content-Encoding: gzip' . "\r\n"
. 'Content-Type: application/javascript' . "\r\n"
. 'Date: Sun, 18 Nov 2012 16:16:08 GMT' . "\r\n"
. 'Server: nginx/1.1.19' . "\r\n"
. 'Set-Cookie: baz=bah; domain=www.domain.com; path=/' . "\r\n"
. 'Set-Cookie: joe=test; domain=www.domain.com; path=/' . "\r\n"
. 'Vary: Accept-Encoding' . "\r\n"
. 'X-Powered-By: PHP/5.3.10-1ubuntu3.4' . "\r\n"
. 'Connection: keep-alive' . "\r\n";
$response = Response::fromString($rawHeaders);
$client->setResponse($response);
$cookies->addCookiesFromResponse($client->getResponse(), $client->getUri());
$client->addCookie($cookies->getMatchingCookies($client->getUri()));
$this->assertEquals(4, count($client->getCookies()));
}
public function testClientRetrievesUppercaseHttpMethodFromRequestObject()
{
$client = new Client();
$client->setMethod('post');
$this->assertEquals(Client::ENC_URLENCODED, $client->getEncType());
}
public function testAcceptEncodingHeaderWorksProperly()
{
$method = new ReflectionMethod(Client::class, 'prepareHeaders');
$method->setAccessible(true);
$requestString = 'GET http://www.domain.com/index.php HTTP/1.1' . "\r\n"
. 'Host: domain.com' . "\r\n"
. 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:16.0) Gecko/20100101 Firefox/16.0' . "\r\n"
. 'Accept: */*' . "\r\n"
. 'Accept-Language: en-US,en;q=0.5' . "\r\n"
. 'Accept-Encoding: gzip, deflate' . "\r\n"
. 'Connection: keep-alive' . "\r\n";
$request = Request::fromString($requestString);
$adapter = new Test();
$client = new Client('http://www.domain.com/');
$client->setAdapter($adapter);
$client->setRequest($request);
$rawHeaders = 'HTTP/1.1 200 OK' . "\r\n"
. 'Access-Control-Allow-Origin: *' . "\r\n"
. 'Content-Encoding: gzip, deflate' . "\r\n"
. 'Content-Type: application/javascript' . "\r\n"
. 'Date: Sun, 18 Nov 2012 16:16:08 GMT' . "\r\n"
. 'Server: nginx/1.1.19' . "\r\n"
. 'Vary: Accept-Encoding' . "\r\n"
. 'X-Powered-By: PHP/5.3.10-1ubuntu3.4' . "\r\n"
. 'Connection: keep-alive' . "\r\n";
$response = Response::fromString($rawHeaders);
$client->getAdapter()->setResponse($response);
$headers = $method->invoke($client, $requestString, $client->getUri());
$this->assertEquals('gzip, deflate', $headers['Accept-Encoding']);
}
public function testIfZeroValueCookiesCanBeSet()
{
$client = new Client();
$client->addCookie('test', 0);
$client->addCookie('test2', '0');
$client->addCookie('test3', false);
}
public function testIfNullValueCookiesThrowsException()
{
$client = new Client();
$this->expectException(HttpException\InvalidArgumentException::class);
$client->addCookie('test', null);
}
public function testIfCookieHeaderCanBeSet()
{
$header = [new SetCookie('foo', 'bar')];
$client = new Client();
$client->addCookie($header);
$cookies = $client->getCookies();
$this->assertEquals(1, count($cookies));
$this->assertEquals($header[0], $cookies['foo']);
}
public function testIfArrayOfHeadersCanBeSet()
{
$headers = [
new SetCookie('foo'),
new SetCookie('bar'),
];
$client = new Client();
$client->addCookie($headers);
$cookies = $client->getCookies();
$this->assertEquals(2, count($cookies));
}
public function testIfArrayIteratorOfHeadersCanBeSet()
{
$headers = new ArrayIterator([
new SetCookie('foo'),
new SetCookie('bar'),
]);
$client = new Client();
$client->addCookie($headers);
$cookies = $client->getCookies();
$this->assertEquals(2, count($cookies));
}
/**
* @group 2774
* @group 2745
*/
public function testArgSeparatorDefaultsToIniSetting()
{
$argSeparator = ini_get('arg_separator.output');
$client = new Client();
$this->assertEquals($argSeparator, $client->getArgSeparator());
}
/**
* @group 2774
* @group 2745
*/
public function testCanOverrideArgSeparator()
{
$client = new Client();
$client->setArgSeparator(';');
$this->assertEquals(';', $client->getArgSeparator());
}
public function testClientUsesAcceptEncodingHeaderFromRequestObject()
{
$client = new Client();
$client->setAdapter(Test::class);
$request = $client->getRequest();
$acceptEncodingHeader = new AcceptEncoding();
$acceptEncodingHeader->addEncoding('foo', 1);
$request->getHeaders()->addHeader($acceptEncodingHeader);
$client->send();
$rawRequest = $client->getLastRawRequest();
$this->assertNotContains('Accept-Encoding: gzip, deflate', $rawRequest, '', true);
$this->assertNotContains('Accept-Encoding: identity', $rawRequest, '', true);
$this->assertContains('Accept-Encoding: foo', $rawRequest);
}
public function testEncodeAuthHeaderWorksAsExpected()
{
$encoded = Client::encodeAuthHeader('test', 'test');
$this->assertEquals('Basic ' . base64_encode('test:test'), $encoded);
}
public function testEncodeAuthHeaderThrowsExceptionWhenUsernameContainsSemiColon()
{
$this->expectException(ClientException\InvalidArgumentException::class);
Client::encodeAuthHeader('test:', 'test');
}
public function testEncodeAuthHeaderThrowsExceptionWhenInvalidAuthTypeIsUsed()
{
$this->expectException(ClientException\InvalidArgumentException::class);
Client::encodeAuthHeader('test', 'test', 'test');
}
public function testIfMaxredirectWorksCorrectly()
{
$testAdapter = new Test();
// first response, contains a redirect
$testAdapter->setResponse(
'HTTP/1.1 303 See Other' . "\r\n"
. 'Location: http://www.example.org/part2' . "\r\n\r\n"
. 'Page #1'
);
// seconds response, contains a redirect
$testAdapter->addResponse(
'HTTP/1.1 303 See Other' . "\r\n"
. 'Location: http://www.example.org/part3' . "\r\n\r\n"
. 'Page #2'
);
// third response
$testAdapter->addResponse(
'HTTP/1.1 303 See Other' . "\r\n\r\n"
. 'Page #3'
);
// create a client which allows one redirect at most!
$client = new Client('http://www.example.org/part1', [
'adapter' => $testAdapter,
'maxredirects' => 1,
'storeresponse' => true,
]);
// do the request
$response = $client->setMethod('GET')->send();
// response should be the second response, since third response should not
// be requested, due to the maxredirects = 1 limit
$this->assertEquals($response->getContent(), 'Page #2');
}
public function testIfClientDoesNotLooseAuthenticationOnRedirect()
{
// set up user credentials
$user = 'username123';
$password = 'password456';
$encoded = Client::encodeAuthHeader($user, $password, Client::AUTH_BASIC);
// set up two responses that simulate a redirection
$testAdapter = new Test();
$testAdapter->setResponse(
'HTTP/1.1 303 See Other' . "\r\n"
. 'Location: http://www.example.org/part2' . "\r\n\r\n"
. 'The URL of this page has changed.'
);
$testAdapter->addResponse(
'HTTP/1.1 200 OK' . "\r\n\r\n"
. 'Welcome to this Website.'
);
// create client with HTTP basic authentication
$client = new Client('http://www.example.org/part1', [
'adapter' => $testAdapter,
'maxredirects' => 1,
]);
$client->setAuth($user, $password, Client::AUTH_BASIC);
// do request
$client->setMethod('GET')->send();
// the last request should contain the Authorization header
$this->assertContains($encoded, $client->getLastRawRequest());
}
public function testIfClientDoesNotForwardAuthenticationToForeignHost()
{
// set up user credentials
$user = 'username123';
$password = 'password456';
$encoded = Client::encodeAuthHeader($user, $password, Client::AUTH_BASIC);
$testAdapter = new Test();
$client = new Client(null, ['adapter' => $testAdapter]);
// set up two responses that simulate a redirection from example.org to example.com
$testAdapter->setResponse(
'HTTP/1.1 303 See Other' . "\r\n"
. 'Location: http://example.com/part2' . "\r\n\r\n"
. 'The URL of this page has changed.'
);
$testAdapter->addResponse(
'HTTP/1.1 200 OK' . "\r\n\r\n"
. 'Welcome to this Website.'
);
// set auth and do request
$client->setUri('http://example.org/part1')
->setAuth($user, $password, Client::AUTH_BASIC);
$client->setMethod('GET')->send();
// the last request should NOT contain the Authorization header,
// because example.com is different from example.org
$this->assertNotContains($encoded, $client->getLastRawRequest());
// set up two responses that simulate a redirection from example.org to sub.example.org
$testAdapter->setResponse(
'HTTP/1.1 303 See Other' . "\r\n"
. 'Location: http://sub.example.org/part2' . "\r\n\r\n"
. 'The URL of this page has changed.'
);
$testAdapter->addResponse(
'HTTP/1.1 200 OK' . "\r\n\r\n"
. 'Welcome to this Website.'
);
// set auth and do request
$client->setUri('http://example.org/part1')
->setAuth($user, $password, Client::AUTH_BASIC);
$client->setMethod('GET')->send();
// the last request should contain the Authorization header,
// because sub.example.org is a subdomain unter example.org
$this->assertContains($encoded, $client->getLastRawRequest());
// set up two responses that simulate a rediration from sub.example.org to example.org
$testAdapter->setResponse(
'HTTP/1.1 303 See Other' . "\r\n"
. 'Location: http://example.org/part2' . "\r\n\r\n"
. 'The URL of this page has changed.'
);
$testAdapter->addResponse(
'HTTP/1.1 200 OK' . "\r\n\r\n"
. 'Welcome to this Website.'
);
// set auth and do request
$client->setUri('http://sub.example.org/part1')
->setAuth($user, $password, Client::AUTH_BASIC);
$client->setMethod('GET')->send();
// the last request should NOT contain the Authorization header,
// because example.org is not a subdomain unter sub.example.org
$this->assertNotContains($encoded, $client->getLastRawRequest());
}
public function testAdapterAlwaysReachableIfSpecified()
{
$testAdapter = new Test();
$client = new Client('http://www.example.org/', [
'adapter' => $testAdapter,
]);
$this->assertSame($testAdapter, $client->getAdapter());
}
public function testPrepareHeadersCreateRightHttpField()
{
$body = json_encode(['foofoo' => 'barbar']);
$client = new Client();
$prepareHeadersReflection = new ReflectionMethod($client, 'prepareHeaders');
$prepareHeadersReflection->setAccessible(true);
$request = new Request();
$request->getHeaders()->addHeaderLine('content-type', 'application/json');
$request->getHeaders()->addHeaderLine('content-length', strlen($body));
$client->setRequest($request);
$client->setEncType('application/json');
$this->assertSame($client->getRequest(), $request);
$headers = $prepareHeadersReflection->invoke($client, $body, new Http('http://localhost:5984'));
$this->assertArrayNotHasKey('content-type', $headers);
$this->assertArrayHasKey('Content-Type', $headers);
$this->assertArrayNotHasKey('content-length', $headers);
$this->assertArrayHasKey('Content-Length', $headers);
}
public function testPrepareHeadersCurlDigestAuthentication()
{
$body = json_encode(['foofoo' => 'barbar']);
$client = new Client();
$prepareHeadersReflection = new ReflectionMethod($client, 'prepareHeaders');
$prepareHeadersReflection->setAccessible(true);
$request = new Request();
$request->getHeaders()->addHeaderLine('Authorization: Digest');
$request->getHeaders()->addHeaderLine('content-type', 'application/json');
$request->getHeaders()->addHeaderLine('content-length', strlen($body));
$client->setRequest($request);
$this->assertSame($client->getRequest(), $request);
$headers = $prepareHeadersReflection->invoke($client, $body, new Http('http://localhost:5984'));
$this->assertInternalType('array', $headers);
$this->assertArrayHasKey('Authorization', $headers);
$this->assertContains('Digest', $headers['Authorization']);
}
/**
* @group 6301
*/
public function testCanSpecifyCustomAuthMethodsInExtendingClasses()
{
$client = new ExtendedClient();
$client->setAuth('username', 'password', ExtendedClient::AUTH_CUSTOM);
$this->assertAttributeEquals(
[
'user' => 'username',
'password' => 'password',
'type' => ExtendedClient::AUTH_CUSTOM,
],
'auth',
$client
);
}
/**
* @group 6231
*/
public function testHttpQueryParametersCastToString()
{
$client = new Client();
$adapter = $this->createMock(AdapterInterface::class);
$client->setAdapter($adapter);
$request = new Request();
$request->setUri('http://example.com/');
$request->getQuery()->set('foo', 'bar');
$response = new Response();
$adapter
->expects($this->once())
->method('write')
->with(Request::METHOD_GET, 'http://example.com/?foo=bar');
$adapter
->expects($this->any())
->method('read')
->will($this->returnValue($response->toString()));
$client->send($request);
}
/**
* @group 6959
*/
public function testClientRequestMethod()
{
$request = new Request();
$request->setMethod(Request::METHOD_POST);
$request->getPost()->set('data', 'random');
$client = new Client();
$client->setAdapter(Test::class);
$client->send($request);
$this->assertSame(Client::ENC_URLENCODED, $client->getEncType());
}
/**
* @group 7332
*/
public function testAllowsClearingEncType()
{
$client = new Client();
$client->setEncType('application/x-www-form-urlencoded');
$this->assertEquals('application/x-www-form-urlencoded', $client->getEncType());
$client->setEncType(null);
$this->assertNull($client->getEncType());
}
/**
* @see https://github.com/zendframework/zend-http/issues/33
*/
public function testFormUrlEncodeSeparator()
{
$client = new Client();
$client->setEncType('application/x-www-form-urlencoded');
$request = new Request();
$request->setMethod(Request::METHOD_POST);
$request->getPost()->set('foo', 'bar');
$request->getPost()->set('baz', 'foo');
ini_set('arg_separator.output', '$');
$client->setAdapter(Test::class);
$client->send($request);
$rawRequest = $client->getLastRawRequest();
$this->assertContains('foo=bar&baz=foo', $rawRequest);
}
public function uriDataProvider()
{
return [
'valid-relative' => ['/example', true],
'invalid-absolute' => ['http://localhost/example', false],
];
}
/**
* @dataProvider uriDataProvider
*/
public function testUriCorrectlyDeterminesWhetherOrNotItIsAValidRelativeUri($uri, $isValidRelativeURI)
{
$client = new Client($uri);
$this->assertSame($isValidRelativeURI, $client->getUri()->isValidRelative());
$client->setAdapter(Test::class);
$client->send();
$this->assertSame($isValidRelativeURI, $client->getUri()->isValidRelative());
}
public function portChangeDataProvider()
{
return [
'default-https' => ['https://localhost/example', 443],
'default-http' => ['http://localhost/example', 80]
];
}
/**
* @dataProvider portChangeDataProvider
*/
public function testUriPortIsSetToAppropriateDefaultValueWhenAnUriOmittingThePortIsProvided($absoluteURI, $port)
{
$client = new Client();
$client->getUri()->setPort(null);
$client->setUri($absoluteURI);
$this->assertSame($port, $client->getUri()->getPort());
$client->setAdapter(Test::class);
$client->send();
$this->assertSame($port, $client->getUri()->getPort());
}
public function testUriPortIsNotSetWhenUriIsRelative()
{
$client = new Client('/example');
$this->assertNull($client->getUri()->getPort());
$client->setAdapter(Test::class);
$client->send();
$this->assertNull($client->getUri()->getPort());
}
public function cookies()
{
yield 'name-value' => [['cookie-name' => 'cookie-value']];
yield 'SetCookie' => [[new SetCookie('cookie-name', 'cookie-value')]];
}
/**
* @dataProvider cookies
*/
public function testSetCookies(array $cookies)
{
$client = new Client();
$client->setCookies($cookies);
self::assertCount(1, $client->getCookies());
self::assertContainsOnlyInstancesOf(SetCookie::class, $client->getCookies());
}
public function testSetCookieAcceptOnlyArray()
{
$client = new Client();
$this->expectException(HttpException\InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid cookies passed as parameter, it must be an array');
$client->setCookies(new SetCookie('name', 'value'));
}
/**
* @return AdapterInterface[]
*/
public function adapterWithStreamSupport()
{
yield 'curl' => [new Curl()];
yield 'proxy' => [new Proxy()];
yield 'socket' => [new Socket()];
}
/**
* @dataProvider adapterWithStreamSupport
*/
public function testStreamCompression(AdapterInterface $adapter)
{
$tmpFile = tempnam(sys_get_temp_dir(), 'stream');
$client = new Client('https://www.gnu.org/licenses/gpl-3.0.txt');
$client->setAdapter($adapter);
$client->setStream($tmpFile);
$client->send();
$response = $client->getResponse();
self::assertSame($response->getBody(), file_get_contents($tmpFile));
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/HeaderTest.php | test/HeaderTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2019 Zend Technologies USA Inc. (https://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http;
use PHPUnit\Framework\TestCase;
use Zend\Http\Exception\InvalidArgumentException;
use Zend\Http\Header;
class HeaderTest extends TestCase
{
public function header()
{
// @codingStandardsIgnoreStart
yield Header\AcceptRanges::class => [Header\AcceptRanges::class, 'Accept-Ranges'];
yield Header\AuthenticationInfo::class => [Header\AuthenticationInfo::class, 'Authentication-Info'];
yield Header\Authorization::class => [Header\Authorization::class, 'Authorization'];
yield Header\ContentDisposition::class => [Header\ContentDisposition::class, 'Content-Disposition'];
yield Header\ContentEncoding::class => [Header\ContentEncoding::class, 'Content-Encoding'];
yield Header\ContentLanguage::class => [Header\ContentLanguage::class, 'Content-Language'];
yield Header\ContentLength::class => [Header\ContentLength::class, 'Content-Length'];
yield Header\ContentMD5::class => [Header\ContentMD5::class, 'Content-MD5'];
yield Header\ContentRange::class => [Header\ContentRange::class, 'Content-Range'];
yield Header\ContentTransferEncoding::class => [Header\ContentTransferEncoding::class, 'Content-Transfer-Encoding'];
yield Header\ContentType::class => [Header\ContentType::class, 'Content-Type'];
yield Header\Etag::class => [Header\Etag::class, 'Etag'];
yield Header\Expect::class => [Header\Expect::class, 'Expect'];
yield Header\From::class => [Header\From::class, 'From'];
yield Header\Host::class => [Header\Host::class, 'Host'];
yield Header\IfMatch::class => [Header\IfMatch::class, 'If-Match'];
yield Header\IfNoneMatch::class => [Header\IfNoneMatch::class, 'If-None-Match'];
yield Header\IfRange::class => [Header\IfRange::class, 'If-Range'];
yield Header\KeepAlive::class => [Header\KeepAlive::class, 'Keep-Alive'];
yield Header\MaxForwards::class => [Header\MaxForwards::class, 'Max-Forwards'];
yield Header\Origin::class => [Header\Origin::class, 'Origin'];
yield Header\Pragma::class => [Header\Pragma::class, 'Pragma'];
yield Header\ProxyAuthenticate::class => [Header\ProxyAuthenticate::class, 'Proxy-Authenticate'];
yield Header\ProxyAuthorization::class => [Header\ProxyAuthorization::class, 'Proxy-Authorization'];
yield Header\Range::class => [Header\Range::class, 'Range'];
yield Header\Refresh::class => [Header\Refresh::class, 'Refresh'];
yield Header\Server::class => [Header\Server::class, 'Server'];
yield Header\TE::class => [Header\TE::class, 'TE'];
yield Header\Trailer::class => [Header\Trailer::class, 'Trailer'];
yield Header\TransferEncoding::class => [Header\TransferEncoding::class, 'Transfer-Encoding'];
yield Header\Upgrade::class => [Header\Upgrade::class, 'Upgrade'];
yield Header\UserAgent::class => [Header\UserAgent::class, 'User-Agent'];
yield Header\Vary::class => [Header\Vary::class, 'Vary'];
yield Header\Via::class => [Header\Via::class, 'Via'];
yield Header\Warning::class => [Header\Warning::class, 'Warning'];
yield Header\WWWAuthenticate::class => [Header\WWWAuthenticate::class, 'WWW-Authenticate'];
// @codingStandardsIgnoreEnd
}
/**
* @dataProvider header
*
* @param string $class
* @param string $name
*/
public function testThrowsExceptionIfInvalidHeaderLine($class, $name)
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid header line for ' . $name . ' string');
$class::fromString($name . '-Foo: bar');
}
/**
* @dataProvider header
*
* @param string $class
* @param string $name
*/
public function testCaseInsensitiveHeaderName($class, $name)
{
$header1 = $class::fromString(strtoupper($name) . ': foo');
self::assertSame('foo', $header1->getFieldValue());
$header2 = $class::fromString(strtolower($name) . ': bar');
self::assertSame('bar', $header2->getFieldValue());
}
/**
* @dataProvider header
*
* @param string $class
* @param string $name
*/
public function testDefaultValues($class, $name)
{
$header = new $class();
self::assertSame('', $header->getFieldValue());
self::assertSame($name, $header->getFieldName());
self::assertSame($name . ': ', $header->toString());
}
/**
* @dataProvider header
*
* @param string $class
* @param string $name
*/
public function testSetValueViaConstructor($class, $name)
{
$header = new $class('foo-bar');
self::assertSame('foo-bar', $header->getFieldValue());
self::assertSame($name . ': foo-bar', $header->toString());
}
/**
* @dataProvider header
*
* @param string $class
* @param string $name
*
* Note: in theory this is invalid, as we would expect value to be string|null.
* Null is default value but it is converted to string.
*/
public function testSetIntValueViaConstructor($class, $name)
{
$header = new $class(100);
self::assertSame('100', $header->getFieldValue());
self::assertSame($name . ': 100', $header->toString());
}
/**
* @dataProvider header
*
* @param string $class
* @param string $name
*/
public function testSetZeroStringValueViaConstructor($class, $name)
{
$header = new $class('0');
self::assertSame('0', $header->getFieldValue());
self::assertSame($name . ': 0', $header->toString());
}
/**
* @dataProvider header
*
* @param string $class
* @param string $name
*/
public function testFromStringWithNumber($class, $name)
{
$header = $class::fromString($name . ': 100');
self::assertSame('100', $header->getFieldValue());
self::assertSame($name . ': 100', $header->toString());
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/ResponseTest.php | test/ResponseTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http;
use PHPUnit\Framework\TestCase;
use Zend\Http\Exception\InvalidArgumentException;
use Zend\Http\Exception\RuntimeException;
use Zend\Http\Header\GenericHeader;
use Zend\Http\Headers;
use Zend\Http\Response;
class ResponseTest extends TestCase
{
public function validHttpVersions()
{
yield 'http/1.0' => ['1.0'];
yield 'http/1.1' => ['1.1'];
yield 'http/2' => ['2'];
}
public function validResponseHttpVersionProvider()
{
$responseTemplate = "HTTP/%s 200 OK\r\n\r\nFoo Bar";
foreach ($this->validHttpVersions() as $testCase => $data) {
$version = array_shift($data);
yield $testCase => [
'response' => sprintf($responseTemplate, $version),
'expectedVersion' => $version,
'expectedStatus' => '200',
'expectedContent' => 'Foo Bar',
];
}
}
/**
* @dataProvider validResponseHttpVersionProvider
* @param string $string Response string
* @param string $expectedVersion
* @param string $expectedStatus
* @param string $expectedContent
*/
public function testResponseFactoryFromStringCreatesValidResponse(
$string,
$expectedVersion,
$expectedStatus,
$expectedContent
) {
$response = Response::fromString($string);
$this->assertEquals($expectedVersion, $response->getVersion());
$this->assertEquals($expectedStatus, $response->getStatusCode());
$this->assertEquals($expectedContent, $response->getContent());
}
/**
* @dataProvider validHttpVersions
* @param string $version
*/
public function testResponseCanRenderStatusLineUsingDefaultReasonPhrase($version)
{
$expected = sprintf('HTTP/%s 404 Not Found', $version);
$response = new Response();
$response->setVersion($version);
$response->setStatusCode(Response::STATUS_CODE_404);
$this->assertEquals($expected, $response->renderStatusLine());
}
/**
* @dataProvider validHttpVersions
* @param string $version
*/
public function testResponseCanRenderStatusLineUsingCustomReasonPhrase($version)
{
$expected = sprintf('HTTP/%s 404 Foo Bar', $version);
$response = new Response();
$response->setVersion($version);
$response->setStatusCode(Response::STATUS_CODE_404);
$response->setReasonPhrase('Foo Bar');
$this->assertEquals($expected, $response->renderStatusLine());
}
public function testInvalidHTTP2VersionString()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('A valid response status line was not found in the provided string');
$string = 'HTTP/2.0 200 OK' . "\r\n\r\n" . 'Foo Bar';
$response = \Zend\Http\Response::fromString($string);
}
public function testResponseUsesHeadersContainerByDefault()
{
$response = new Response();
$this->assertInstanceOf(Headers::class, $response->getHeaders());
}
public function testRequestCanSetHeaders()
{
$response = new Response();
$headers = new Headers();
$ret = $response->setHeaders($headers);
$this->assertInstanceOf(Response::class, $ret);
$this->assertSame($headers, $response->getHeaders());
}
public function validStatusCode()
{
for ($i = 100; $i <= 599; ++$i) {
yield $i => [$i];
}
}
/**
* @dataProvider validStatusCode
*
* @param int $statusCode
*/
public function testResponseCanSetStatusCode($statusCode)
{
$response = new Response();
$this->assertSame(200, $response->getStatusCode());
$response->setStatusCode($statusCode);
$this->assertSame($statusCode, $response->getStatusCode());
}
public function testResponseSetStatusCodeThrowsExceptionOnInvalidCode()
{
$response = new Response();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid status code');
$response->setStatusCode(606);
}
public function testResponseGetReasonPhraseWillReturnEmptyPhraseAsDefault()
{
$response = new Response();
$response->setCustomStatusCode(998);
$this->assertSame('HTTP/1.1 998' . "\r\n\r\n", (string) $response);
}
public function testResponseCanSetCustomStatusCode()
{
$response = new Response();
$this->assertEquals(200, $response->getStatusCode());
$response->setCustomStatusCode('999');
$this->assertEquals(999, $response->getStatusCode());
}
public function testResponseSetCustomStatusCodeThrowsExceptionOnInvalidCode()
{
$response = new Response();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid status code "foo"; must be an integer between 100 and 599, inclusive');
$response->setStatusCode('foo');
}
public function testResponseEndsAtStatusCode()
{
$string = 'HTTP/1.0 200' . "\r\n\r\n" . 'Foo Bar';
$response = Response::fromString($string);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Foo Bar', $response->getContent());
}
public function testResponseHasZeroLengthReasonPhrase()
{
// Space after status code is mandatory,
// though, reason phrase can be empty.
// @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1
$string = 'HTTP/1.0 200 ' . "\r\n\r\n" . 'Foo Bar';
$response = Response::fromString($string);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Foo Bar', $response->getContent());
// Reason phrase would fallback to default reason phrase.
$this->assertEquals('OK', $response->getReasonPhrase());
}
public function testGzipResponse()
{
$responseTest = file_get_contents(__DIR__ . '/_files/response_gzip');
$res = Response::fromString($responseTest);
$this->assertEquals('gzip', $res->getHeaders()->get('Content-encoding')->getFieldValue());
$this->assertEquals('0b13cb193de9450aa70a6403e2c9902f', md5($res->getBody()));
$this->assertEquals('f24dd075ba2ebfb3bf21270e3fdc5303', md5($res->getContent()));
}
public function testGzipResponseWithEmptyBody()
{
$responseTest = <<<'REQ'
HTTP/1.1 200 OK
Date: Sun, 25 Jun 2006 19:36:47 GMT
Server: Apache
X-powered-by: PHP/5.1.4-pl3-gentoo
Content-encoding: gzip
Vary: Accept-Encoding
Content-length: 0
Connection: close
Content-type: text/html
REQ;
$res = Response::fromString($responseTest);
$this->assertEquals('gzip', $res->getHeaders()->get('Content-encoding')->getFieldValue());
$this->assertSame('', $res->getBody());
$this->assertSame('', $res->getContent());
}
public function testDeflateResponse()
{
$responseTest = file_get_contents(__DIR__ . '/_files/response_deflate');
$res = Response::fromString($responseTest);
$this->assertEquals('deflate', $res->getHeaders()->get('Content-encoding')->getFieldValue());
$this->assertEquals('0b13cb193de9450aa70a6403e2c9902f', md5($res->getBody()));
$this->assertEquals('ad62c21c3aa77b6a6f39600f6dd553b8', md5($res->getContent()));
}
public function testDeflateResponseWithEmptyBody()
{
$responseTest = <<<'REQ'
HTTP/1.1 200 OK
Date: Sun, 25 Jun 2006 19:38:02 GMT
Server: Apache
X-powered-by: PHP/5.1.4-pl3-gentoo
Content-encoding: deflate
Vary: Accept-Encoding
Content-length: 0
Connection: close
Content-type: text/html
REQ;
$res = Response::fromString($responseTest);
$this->assertEquals('deflate', $res->getHeaders()->get('Content-encoding')->getFieldValue());
$this->assertSame('', $res->getBody());
$this->assertSame('', $res->getContent());
}
/**
* Make sure wer can handle non-RFC complient "deflate" responses.
*
* Unlike stanrdard 'deflate' response, those do not contain the zlib header
* and trailer. Unfortunately some buggy servers (read: IIS) send those and
* we need to support them.
*
* @link http://framework.zend.com/issues/browse/ZF-6040
*/
public function testNonStandardDeflateResponseZF6040()
{
$this->markTestSkipped('Not correctly handling non-RFC complient "deflate" responses');
$responseTest = file_get_contents(__DIR__ . '/_files/response_deflate_iis');
$res = Response::fromString($responseTest);
$this->assertEquals('deflate', $res->getHeaders()->get('Content-encoding')->getFieldValue());
$this->assertEquals('d82c87e3d5888db0193a3fb12396e616', md5($res->getBody()));
$this->assertEquals('c830dd74bb502443cf12514c185ff174', md5($res->getContent()));
}
public function testChunkedResponse()
{
$responseTest = file_get_contents(__DIR__ . '/_files/response_chunked');
$res = Response::fromString($responseTest);
$this->assertEquals('chunked', $res->getHeaders()->get('Transfer-encoding')->getFieldValue());
$this->assertEquals('0b13cb193de9450aa70a6403e2c9902f', md5($res->getBody()));
$this->assertEquals('c0cc9d44790fa2a58078059bab1902a9', md5($res->getContent()));
}
public function testChunkedResponseCaseInsensitiveZF5438()
{
$responseTest = file_get_contents(__DIR__ . '/_files/response_chunked_case');
$res = Response::fromString($responseTest);
$this->assertEquals('chunked', strtolower($res->getHeaders()->get('Transfer-encoding')->getFieldValue()));
$this->assertEquals('0b13cb193de9450aa70a6403e2c9902f', md5($res->getBody()));
$this->assertEquals('c0cc9d44790fa2a58078059bab1902a9', md5($res->getContent()));
}
/**
* @param int $chunksize the data size of the chunk to create
* @return string a chunk of data for embedding inside a chunked response
*/
private function makeChunk($chunksize)
{
return sprintf("%d\r\n%s\r\n", $chunksize, str_repeat('W', $chunksize));
}
/**
* @param Response $response
* @return float the time that calling the getBody function took on the response
*/
private function getTimeForGetBody(Response $response)
{
$timeStart = microtime(true);
$response->getBody();
return microtime(true) - $timeStart;
}
/**
* @small
*/
public function testChunkedResponsePerformance()
{
$headers = new Headers();
$headers->addHeaders([
'Date' => 'Sun, 25 Jun 2006 19:55:19 GMT',
'Server' => 'Apache',
'X-powered-by' => 'PHP/5.1.4-pl3-gentoo',
'Connection' => 'close',
'Transfer-encoding' => 'chunked',
'Content-type' => 'text/html',
]);
$response = new Response();
$response->setHeaders($headers);
// avoid flakiness, repeat test
$timings = [];
for ($i = 0; $i < 4; $i++) {
// get baseline for timing: 2000 x 1 Byte chunks
$responseData = str_repeat($this->makeChunk(1), 2000);
$response->setContent($responseData);
$time1 = $this->getTimeForGetBody($response);
// 'worst case' response, where 2000 1 Byte chunks are followed by a 10 MB Chunk
$responseData2 = $responseData . $this->makeChunk(10000000);
$response->setContent($responseData2);
$time2 = $this->getTimeForGetBody($response);
$timings[] = floor($time2 / $time1);
}
array_shift($timings); // do not measure first iteration
// make sure that the worst case packet will have an equal timing as the baseline
$errMsg = 'Chunked response is not parsing large packets efficiently! Timings:';
$this->assertLessThan(20, min($timings), $errMsg . print_r($timings, true));
}
public function testLineBreaksCompatibility()
{
$responseTestLf = $this->readResponse('response_lfonly');
$resLf = Response::fromString($responseTestLf);
$responseTestCrlf = $this->readResponse('response_crlf');
$resCrlf = Response::fromString($responseTestCrlf);
$this->assertEquals(
$resLf->getHeaders()->toString(),
$resCrlf->getHeaders()->toString(),
'Responses headers do not match'
);
$this->markTestIncomplete('Something is fishy with the response bodies in the test responses');
$this->assertEquals($resLf->getBody(), $resCrlf->getBody(), 'Response bodies do not match');
}
public function test404IsClientErrorAndNotFound()
{
$responseTest = $this->readResponse('response_404');
$response = Response::fromString($responseTest);
$this->assertEquals(404, $response->getStatusCode(), 'Response code is expected to be 404, but it\'s not.');
$this->assertTrue($response->isClientError(), 'Response is an error, but isClientError() returned false');
$this->assertFalse($response->isForbidden(), 'Response is an error, but isForbidden() returned true');
$this->assertFalse($response->isInformational(), 'Response is an error, but isInformational() returned true');
$this->assertTrue($response->isNotFound(), 'Response is an error, but isNotFound() returned false');
$this->assertFalse($response->isGone(), 'Response is an error, but isGone() returned true');
$this->assertFalse($response->isOk(), 'Response is an error, but isOk() returned true');
$this->assertFalse($response->isServerError(), 'Response is an error, but isServerError() returned true');
$this->assertFalse($response->isRedirect(), 'Response is an error, but isRedirect() returned true');
$this->assertFalse($response->isSuccess(), 'Response is an error, but isSuccess() returned true');
}
public function test410IsGone()
{
$responseTest = $this->readResponse('response_410');
$response = Response::fromString($responseTest);
$this->assertEquals(410, $response->getStatusCode(), 'Response code is expected to be 410, but it\'s not.');
$this->assertTrue($response->isClientError(), 'Response is an error, but isClientError() returned false');
$this->assertFalse($response->isForbidden(), 'Response is an error, but isForbidden() returned true');
$this->assertFalse($response->isInformational(), 'Response is an error, but isInformational() returned true');
$this->assertFalse($response->isNotFound(), 'Response is an error, but isNotFound() returned true');
$this->assertTrue($response->isGone(), 'Response is an error, but isGone() returned false');
$this->assertFalse($response->isOk(), 'Response is an error, but isOk() returned true');
$this->assertFalse($response->isServerError(), 'Response is an error, but isServerError() returned true');
$this->assertFalse($response->isRedirect(), 'Response is an error, but isRedirect() returned true');
$this->assertFalse($response->isSuccess(), 'Response is an error, but isSuccess() returned true');
}
public function test500isError()
{
$responseTest = $this->readResponse('response_500');
$response = Response::fromString($responseTest);
$this->assertEquals(500, $response->getStatusCode(), 'Response code is expected to be 500, but it\'s not.');
$this->assertFalse($response->isClientError(), 'Response is an error, but isClientError() returned true');
$this->assertFalse($response->isForbidden(), 'Response is an error, but isForbidden() returned true');
$this->assertFalse($response->isInformational(), 'Response is an error, but isInformational() returned true');
$this->assertFalse($response->isNotFound(), 'Response is an error, but isNotFound() returned true');
$this->assertFalse($response->isGone(), 'Response is an error, but isGone() returned true');
$this->assertFalse($response->isOk(), 'Response is an error, but isOk() returned true');
$this->assertTrue($response->isServerError(), 'Response is an error, but isServerError() returned false');
$this->assertFalse($response->isRedirect(), 'Response is an error, but isRedirect() returned true');
$this->assertFalse($response->isSuccess(), 'Response is an error, but isSuccess() returned true');
}
/**
* @group ZF-5520
*/
public function test302LocationHeaderMatches()
{
$headerName = 'Location';
$headerValue = 'http://www.google.com/ig?hl=en';
$response = Response::fromString($this->readResponse('response_302'));
$responseIis = Response::fromString($this->readResponse('response_302_iis'));
$this->assertEquals($headerValue, $response->getHeaders()->get($headerName)->getFieldValue());
$this->assertEquals($headerValue, $responseIis->getHeaders()->get($headerName)->getFieldValue());
}
public function test300isRedirect()
{
$response = Response::fromString($this->readResponse('response_302'));
$this->assertEquals(302, $response->getStatusCode(), 'Response code is expected to be 302, but it\'s not.');
$this->assertFalse($response->isClientError(), 'Response is an error, but isClientError() returned true');
$this->assertFalse($response->isForbidden(), 'Response is an error, but isForbidden() returned true');
$this->assertFalse($response->isInformational(), 'Response is an error, but isInformational() returned true');
$this->assertFalse($response->isNotFound(), 'Response is an error, but isNotFound() returned true');
$this->assertFalse($response->isGone(), 'Response is an error, but isGone() returned true');
$this->assertFalse($response->isOk(), 'Response is an error, but isOk() returned true');
$this->assertFalse($response->isServerError(), 'Response is an error, but isServerError() returned true');
$this->assertTrue($response->isRedirect(), 'Response is an error, but isRedirect() returned false');
$this->assertFalse($response->isSuccess(), 'Response is an error, but isSuccess() returned true');
}
public function test200Ok()
{
$response = Response::fromString($this->readResponse('response_deflate'));
$this->assertEquals(200, $response->getStatusCode(), 'Response code is expected to be 200, but it\'s not.');
$this->assertFalse($response->isClientError(), 'Response is an error, but isClientError() returned true');
$this->assertFalse($response->isForbidden(), 'Response is an error, but isForbidden() returned true');
$this->assertFalse($response->isInformational(), 'Response is an error, but isInformational() returned true');
$this->assertFalse($response->isNotFound(), 'Response is an error, but isNotFound() returned true');
$this->assertFalse($response->isGone(), 'Response is an error, but isGone() returned true');
$this->assertTrue($response->isOk(), 'Response is an error, but isOk() returned false');
$this->assertFalse($response->isServerError(), 'Response is an error, but isServerError() returned true');
$this->assertFalse($response->isRedirect(), 'Response is an error, but isRedirect() returned true');
$this->assertTrue($response->isSuccess(), 'Response is an error, but isSuccess() returned false');
}
public function test100Continue()
{
$this->markTestIncomplete();
}
public function testAutoMessageSet()
{
$response = Response::fromString($this->readResponse('response_403_nomessage'));
$this->assertEquals(403, $response->getStatusCode(), 'Response status is expected to be 403, but it isn\'t');
$this->assertEquals(
'Forbidden',
$response->getReasonPhrase(),
'Response is 403, but message is not "Forbidden" as expected'
);
// While we're here, make sure it's classified as error...
$this->assertTrue($response->isClientError(), 'Response is an error, but isClientError() returned false');
$this->assertTrue($response->isForbidden(), 'Response is an error, but isForbidden() returned false');
$this->assertFalse($response->isInformational(), 'Response is an error, but isInformational() returned true');
$this->assertFalse($response->isNotFound(), 'Response is an error, but isNotFound() returned true');
$this->assertFalse($response->isGone(), 'Response is an error, but isGone() returned true');
$this->assertFalse($response->isOk(), 'Response is an error, but isOk() returned true');
$this->assertFalse($response->isServerError(), 'Response is an error, but isServerError() returned true');
$this->assertFalse($response->isRedirect(), 'Response is an error, but isRedirect() returned true');
$this->assertFalse($response->isSuccess(), 'Response is an error, but isSuccess() returned true');
}
public function testToString()
{
$responseStr = $this->readResponse('response_404');
$response = Response::fromString($responseStr);
$this->assertEquals(
strtolower(str_replace("\n", "\r\n", $responseStr)),
strtolower($response->toString()),
'Response convertion to string does not match original string'
);
$this->assertEquals(
strtolower(str_replace("\n", "\r\n", $responseStr)),
strtolower((string) $response),
'Response convertion to string does not match original string'
);
}
public function testToStringGzip()
{
$responseStr = $this->readResponse('response_gzip');
$response = Response::fromString($responseStr);
$this->assertEquals(
strtolower($responseStr),
strtolower($response->toString()),
'Response convertion to string does not match original string'
);
$this->assertEquals(
strtolower($responseStr),
strtolower((string) $response),
'Response convertion to string does not match original string'
);
}
public function testGetHeaders()
{
$response = Response::fromString($this->readResponse('response_deflate'));
$headers = $response->getHeaders();
$this->assertEquals(8, count($headers), 'Header count is not as expected');
$this->assertEquals('Apache', $headers->get('Server')->getFieldValue(), 'Server header is not as expected');
$this->assertEquals(
'deflate',
$headers->get('Content-encoding')->getFieldValue(),
'Content-type header is not as expected'
);
}
public function testGetVersion()
{
$response = Response::fromString($this->readResponse('response_chunked'));
$this->assertEquals(1.1, $response->getVersion(), 'Version is expected to be 1.1');
}
public function testUnknownCode()
{
$responseStr = $this->readResponse('response_unknown');
$response = Response::fromString($responseStr);
$this->assertEquals(550, $response->getStatusCode());
}
/**
* Make sure a response with some leading whitespace in the response body
* does not get modified (see ZF-1924)
*/
public function testLeadingWhitespaceBody()
{
$response = Response::fromString($this->readResponse('response_leadingws'));
$this->assertEquals(
$response->getContent(),
"\r\n\t \n\r\tx",
'Extracted body is not identical to expected body'
);
}
/**
* Test that parsing a multibyte-encoded chunked response works.
*
* This can potentially fail on different PHP environments - for example
* when mbstring.func_overload is set to overload strlen().
*/
public function testMultibyteChunkedResponse()
{
$this->markTestSkipped('Looks like the headers are split with \n and the body with \r\n');
$md5 = 'ab952f1617d0e28724932401f2d3c6ae';
$response = Response::fromString($this->readResponse('response_multibyte_body'));
$this->assertEquals($md5, md5($response->getBody()));
}
/**
* Test automatic clean reason phrase
*/
public function testOverrideReasonPraseByStatusCode()
{
$response = new Response();
$response->setStatusCode(200);
$response->setReasonPhrase('Custom reason phrase');
$this->assertEquals('Custom reason phrase', $response->getReasonPhrase());
$response->setStatusCode(400);
$this->assertEquals('Bad Request', $response->getReasonPhrase());
}
public function testromStringFactoryCreatesSingleObjectWithHeaderFolding()
{
$request = Response::fromString("HTTP/1.1 200 OK\r\nFake: foo\r\n -bar");
$headers = $request->getHeaders();
$this->assertEquals(1, $headers->count());
$header = $headers->get('fake');
$this->assertInstanceOf(GenericHeader::class, $header);
$this->assertEquals('Fake', $header->getFieldName());
$this->assertEquals('foo-bar', $header->getFieldValue());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackWhenDeserializing()
{
$this->expectException(RuntimeException::class);
Response::fromString(
"HTTP/1.1 200 OK\r\nAllow: POST\r\nX-Foo: This\ris\r\n\r\nCRLF\nInjection"
);
}
public function test100ContinueFromString()
{
$fixture = 'TOKEN=EC%XXXXXXXXXXXXX&TIMESTAMP=2017%2d10%2d10T09%3a02%3a55Z'
."&CORRELATIONID=XXXXXXXXXX&ACK=Success&VERSION=65%2e1&BUILD=XXXXXXXXXX\r\n";
$request = Response::fromString($this->readResponse('response_100_continue'));
$this->assertEquals(Response::STATUS_CODE_200, $request->getStatusCode());
$this->assertEquals($fixture, $request->getBody());
}
/**
* Helper function: read test response from file
*
* @param string $response
* @return string
*/
protected function readResponse($response)
{
return file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . $response);
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/CookiesTest.php | test/CookiesTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http;
use PHPUnit\Framework\TestCase;
use Zend\Http\Cookies;
use Zend\Http\Header\SetCookie;
use Zend\Http\Headers;
use Zend\Http\PhpEnvironment\Request;
use Zend\Http\Response;
class CookiesTest extends TestCase
{
public function testFromResponseInSetCookie()
{
$response = new Response();
$headers = new Headers();
$header = new SetCookie('foo', 'bar');
$header->setDomain('www.zend.com');
$header->setPath('/');
$headers->addHeader($header);
$response->setHeaders($headers);
$response = Cookies::fromResponse($response, 'http://www.zend.com');
$this->assertSame($header, $response->getCookie('http://www.zend.com', 'foo'));
}
public function testFromResponseInCookie()
{
$response = new Response();
$headers = new Headers();
$header = new SetCookie('foo', 'bar');
$header->setDomain('www.zend.com');
$header->setPath('/');
$headers->addHeader($header);
$response->setHeaders($headers);
$response = Cookies::fromResponse($response, 'http://www.zend.com');
$this->assertSame($header, $response->getCookie('http://www.zend.com', 'foo'));
}
public function testRequestCanHaveArrayCookies()
{
$_COOKIE = [
'test' => [
'a' => 'value_a',
'b' => 'value_b',
],
];
$request = new Request();
$fieldValue = $request->getCookie('test')->getFieldValue();
$this->assertSame('test[a]=value_a; test[b]=value_b', $fieldValue);
$_COOKIE = [
'test' => [
'a' => [
'a1' => 'va1',
'a2' => 'va2',
],
'b' => [
'b1' => 'vb1',
'b2' => 'vb2',
],
],
];
$request = new Request();
$fieldValue = $request->getCookie('test')->getFieldValue();
$this->assertSame('test[a][a1]=va1; test[a][a2]=va2; test[b][b1]=vb1; test[b][b2]=vb2', $fieldValue);
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/RequestTest.php | test/RequestTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use stdClass;
use Zend\Http\Exception\InvalidArgumentException;
use Zend\Http\Exception\RuntimeException;
use Zend\Http\Header\GenericHeader;
use Zend\Http\Headers;
use Zend\Http\Request;
use Zend\Stdlib\Parameters;
use Zend\Uri\Uri;
class RequestTest extends TestCase
{
public function testRequestFromStringFactoryCreatesValidRequest()
{
$string = "GET /foo?myparam=myvalue HTTP/1.1\r\n\r\nSome Content";
$request = Request::fromString($string);
$this->assertEquals(Request::METHOD_GET, $request->getMethod());
$this->assertEquals('/foo?myparam=myvalue', $request->getUri());
$this->assertEquals('myvalue', $request->getQuery()->get('myparam'));
$this->assertEquals(Request::VERSION_11, $request->getVersion());
$this->assertEquals('Some Content', $request->getContent());
}
public function testRequestUsesParametersContainerByDefault()
{
$request = new Request();
$this->assertInstanceOf(Parameters::class, $request->getQuery());
$this->assertInstanceOf(Parameters::class, $request->getPost());
$this->assertInstanceOf(Parameters::class, $request->getFiles());
}
public function testRequestAllowsSettingOfParameterContainer()
{
$request = new Request();
$p = new Parameters();
$request->setQuery($p);
$request->setPost($p);
$request->setFiles($p);
$this->assertSame($p, $request->getQuery());
$this->assertSame($p, $request->getPost());
$this->assertSame($p, $request->getFiles());
$headers = new Headers();
$request->setHeaders($headers);
$this->assertSame($headers, $request->getHeaders());
}
public function testRetrievingASingleValueForParameters()
{
$request = new Request();
$p = new Parameters([
'foo' => 'bar',
]);
$request->setQuery($p);
$request->setPost($p);
$request->setFiles($p);
$this->assertSame('bar', $request->getQuery('foo'));
$this->assertSame('bar', $request->getPost('foo'));
$this->assertSame('bar', $request->getFiles('foo'));
$headers = new Headers();
$h = new GenericHeader('foo', 'bar');
$headers->addHeader($h);
$request->setHeaders($headers);
$this->assertSame($headers, $request->getHeaders());
$this->assertSame($h, $request->getHeaders()->get('foo'));
$this->assertSame($h, $request->getHeader('foo'));
}
public function testParameterRetrievalDefaultValue()
{
$request = new Request();
$p = new Parameters([
'foo' => 'bar',
]);
$request->setQuery($p);
$request->setPost($p);
$request->setFiles($p);
$default = 15;
$this->assertSame($default, $request->getQuery('baz', $default));
$this->assertSame($default, $request->getPost('baz', $default));
$this->assertSame($default, $request->getFiles('baz', $default));
$this->assertSame($default, $request->getHeaders('baz', $default));
$this->assertSame($default, $request->getHeader('baz', $default));
}
public function testRequestPersistsRawBody()
{
$request = new Request();
$request->setContent('foo');
$this->assertEquals('foo', $request->getContent());
}
public function testRequestUsesHeadersContainerByDefault()
{
$request = new Request();
$this->assertInstanceOf(Headers::class, $request->getHeaders());
}
public function testRequestCanSetHeaders()
{
$request = new Request();
$headers = new Headers();
$ret = $request->setHeaders($headers);
$this->assertInstanceOf(Request::class, $ret);
$this->assertSame($headers, $request->getHeaders());
}
public function testRequestCanSetAndRetrieveValidMethod()
{
$request = new Request();
$request->setMethod('POST');
$this->assertEquals('POST', $request->getMethod());
}
public function testRequestCanAlwaysForcesUppecaseMethodName()
{
$request = new Request();
$request->setMethod('get');
$this->assertEquals('GET', $request->getMethod());
}
/**
* @dataProvider uriDataProvider
*
* @param string $uri
*/
public function testRequestCanSetAndRetrieveUri($uri)
{
$request = new Request();
$request->setUri($uri);
$this->assertEquals($uri, $request->getUri());
$this->assertInstanceOf(Uri::class, $request->getUri());
$this->assertEquals($uri, $request->getUri()->toString());
$this->assertEquals($uri, $request->getUriString());
}
public function uriDataProvider()
{
return [
['/foo'],
['/foo#test'],
['/hello?what=true#noway'],
];
}
public function testRequestSetUriWillThrowExceptionOnInvalidArgument()
{
$request = new Request();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('must be an instance of');
$request->setUri(new stdClass());
}
public function testRequestCanSetAndRetrieveVersion()
{
$request = new Request();
$this->assertEquals('1.1', $request->getVersion());
$request->setVersion(Request::VERSION_10);
$this->assertEquals('1.0', $request->getVersion());
}
public function testRequestSetVersionWillThrowExceptionOnInvalidArgument()
{
$request = new Request();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Not valid or not supported HTTP version');
$request->setVersion('1.2');
}
/**
* @dataProvider getMethods
*
* @param string $methodName
*/
public function testRequestMethodCheckWorksForAllMethods($methodName)
{
$request = new Request();
$request->setMethod($methodName);
foreach ($this->getMethods(false, $methodName) as $testMethodName => $testMethodValue) {
$this->assertEquals($testMethodValue, $request->{'is' . $testMethodName}());
}
}
public function testRequestCanBeCastToAString()
{
$request = new Request();
$request->setMethod(Request::METHOD_GET);
$request->setUri('/');
$request->setContent('foo=bar&bar=baz');
$this->assertEquals("GET / HTTP/1.1\r\n\r\nfoo=bar&bar=baz", $request->toString());
}
public function testRequestIsXmlHttpRequest()
{
$request = new Request();
$this->assertFalse($request->isXmlHttpRequest());
$request = new Request();
$request->getHeaders()->addHeaderLine('X_REQUESTED_WITH', 'FooBazBar');
$this->assertFalse($request->isXmlHttpRequest());
$request = new Request();
$request->getHeaders()->addHeaderLine('X_REQUESTED_WITH', 'XMLHttpRequest');
$this->assertTrue($request->isXmlHttpRequest());
}
public function testRequestIsFlashRequest()
{
$request = new Request();
$this->assertFalse($request->isFlashRequest());
$request = new Request();
$request->getHeaders()->addHeaderLine('USER_AGENT', 'FooBazBar');
$this->assertFalse($request->isFlashRequest());
$request = new Request();
$request->getHeaders()->addHeaderLine('USER_AGENT', 'Shockwave Flash');
$this->assertTrue($request->isFlashRequest());
}
/**
* @group 4893
*/
public function testRequestsWithoutHttpVersionAreOK()
{
$requestString = 'GET http://www.domain.com/index.php';
$request = Request::fromString($requestString);
$this->assertEquals($request::METHOD_GET, $request->getMethod());
}
/**
* @param bool $providerContext
* @param null|string $trueMethod
* @return array
*/
public function getMethods($providerContext, $trueMethod = null)
{
$refClass = new ReflectionClass(Request::class);
$return = [];
foreach ($refClass->getConstants() as $cName => $cValue) {
if (substr($cName, 0, 6) == 'METHOD') {
if ($providerContext) {
$return[] = [$cValue];
} else {
$return[strtolower($cValue)] = $trueMethod == $cValue;
}
}
}
return $return;
}
public function testCustomMethods()
{
$request = new Request();
$this->assertTrue($request->getAllowCustomMethods());
$request->setMethod('xcustom');
$this->assertEquals('XCUSTOM', $request->getMethod());
}
public function testDisallowCustomMethods()
{
$request = new Request();
$request->setAllowCustomMethods(false);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid HTTP method passed');
$request->setMethod('xcustom');
}
public function testCustomMethodsFromString()
{
$request = Request::fromString('X-CUS_TOM someurl');
$this->assertTrue($request->getAllowCustomMethods());
$this->assertEquals('X-CUS_TOM', $request->getMethod());
}
public function testDisallowCustomMethodsFromString()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('A valid request line was not found in the provided string');
Request::fromString('X-CUS_TOM someurl', false);
}
public function testAllowCustomMethodsFlagIsSetByFromString()
{
$request = Request::fromString('GET someurl', false);
$this->assertFalse($request->getAllowCustomMethods());
}
public function testFromStringFactoryCreatesSingleObjectWithHeaderFolding()
{
$request = Request::fromString("GET /foo HTTP/1.1\r\nFake: foo\r\n -bar");
$headers = $request->getHeaders();
$this->assertEquals(1, $headers->count());
$header = $headers->get('fake');
$this->assertInstanceOf(GenericHeader::class, $header);
$this->assertEquals('Fake', $header->getFieldName());
$this->assertEquals('foo-bar', $header->getFieldValue());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testCRLFAttack()
{
$this->expectException(RuntimeException::class);
Request::fromString(
"GET /foo HTTP/1.1\r\nHost: example.com\r\nX-Foo: This\ris\r\n\r\nCRLF\nInjection"
);
}
public function testGetHeadersDoesNotRaiseExceptionForInvalidHeaderLines()
{
$request = Request::fromString("GET /foo HTTP/1.1\r\nHost: example.com\r\nUseragent: h4ckerbot");
$headers = $request->getHeaders();
$this->assertFalse($headers->has('User-Agent'));
$this->assertFalse($headers->get('User-Agent'));
$this->assertSame('bar-baz', $request->getHeader('User-Agent', 'bar-baz'));
$this->assertTrue($headers->has('useragent'));
$this->assertInstanceOf(GenericHeader::class, $headers->get('useragent'));
$this->assertSame('h4ckerbot', $headers->get('useragent')->getFieldValue());
$this->assertSame('h4ckerbot', $request->getHeader('useragent')->getFieldValue());
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/TestAsset/ExtendedClient.php | test/TestAsset/ExtendedClient.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\TestAsset;
use Zend\Http\Client;
class ExtendedClient extends Client
{
const AUTH_CUSTOM = 'custom';
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/ProxyAdapterTest.php | test/Client/ProxyAdapterTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
use Zend\Http\Client;
use Zend\Http\Client\Adapter\Proxy;
use Zend\Http\Client\Adapter\Socket;
/**
* Zend_Http_Client_Adapter_Proxy test suite.
*
* In order to run, TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY must point to a working
* proxy server, which can access TESTS_ZEND_HTTP_CLIENT_BASEURI.
*
* See phpunit.xml.dist for more information.
*
* @group Zend_Http
* @group Zend_Http_Client
*/
class ProxyAdapterTest extends SocketTest
{
/** @var string */
protected $host;
/** @var int */
protected $port;
protected function setUp()
{
if (getenv('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY')
&& filter_var(getenv('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY'), FILTER_VALIDATE_BOOLEAN) === false
) {
list($host, $port) = explode(':', getenv('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY'), 2);
if (! $host) {
$this->markTestSkipped('No valid proxy host name or address specified.');
}
$this->host = $host;
$port = (int) $port;
if ($port === 0) {
$port = 8080;
} elseif ($port < 1 || $port > 65535) {
$this->markTestSkipped(sprintf(
'%s is not a valid proxy port number. Should be between 1 and 65535.',
$port
));
}
$this->port = $port;
$user = getenv('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_USER') ?: '';
$pass = getenv('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_PASS') ?: '';
$this->config = [
'adapter' => Proxy::class,
'proxy_host' => $host,
'proxy_port' => $port,
'proxy_user' => $user,
'proxy_pass' => $pass,
];
parent::setUp();
} else {
$this->markTestSkipped(sprintf(
'%s proxy server tests are not enabled in phpunit.xml',
Client::class
));
}
}
/**
* Test that when no proxy is set the adapter falls back to direct connection
*/
public function testFallbackToSocket()
{
$this->_adapter->setOptions([
'proxy_host' => null,
]);
$this->client->setUri($this->baseuri . 'testGetLastRequest.php');
$res = $this->client->setMethod(\Zend\Http\Request::METHOD_TRACE)->send();
if ($res->getStatusCode() == 405 || $res->getStatusCode() == 501) {
$this->markTestSkipped('Server does not allow the TRACE method');
}
$this->assertEquals(
$this->client->getLastRawRequest(),
$res->getBody(),
'Response body should be exactly like the last request'
);
}
public function testGetLastRequest()
{
// This test will never work for the proxy adapter (and shouldn't!)
// because the proxy server modifies the request which is sent back in
// the TRACE response
}
public function testDefaultConfig()
{
$config = $this->_adapter->getConfig();
$this->assertEquals(true, $config['sslverifypeer']);
$this->assertEquals(false, $config['sslallowselfsigned']);
}
/**
* Somehow verification failed for the request through the proxy.
* This could be an issue with Proxy/Socket adapter implementation,
* as issue is not present from command line using curl:
* curl -IL https://framework.zend.com -x 127.0.0.1:8081
*/
public function testUsesProvidedArgSeparator()
{
$this->client->setOptions(['sslverifypeername' => false]);
parent::testUsesProvidedArgSeparator();
}
/**
* HTTP request through the proxy must be with absoluteURI
* https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
* Response contains path, not the absolute URI,
* also Connection: close header is in the different place.
*/
public function testGetLastRawRequest()
{
$this->client->setUri($this->baseuri . 'testHeaders.php');
$this->client->setParameterGet(['someinput' => 'somevalue']);
$this->client->setHeaders([
'X-Powered-By' => 'My Glorious Golden Ass',
]);
$this->client->setMethod('TRACE');
$res = $this->client->send();
if ($res->getStatusCode() == 405 || $res->getStatusCode() == 501) {
$this->markTestSkipped('Server does not allow the TRACE method');
}
list($schema, $host) = explode('://', $this->baseuri);
$host = trim($host, '/');
$this->assertSame(
'TRACE ' . $this->baseuri . 'testHeaders.php?someinput=somevalue HTTP/1.1' . "\r\n"
. 'Host: ' . $host . "\r\n"
. 'Connection: close' . "\r\n"
. 'Accept-Encoding: gzip, deflate' . "\r\n"
. 'User-Agent: Zend\Http\Client' . "\r\n"
. 'X-Powered-By: My Glorious Golden Ass' . "\r\n\r\n",
$this->client->getLastRawRequest()
);
$this->assertSame(
'TRACE /testHeaders.php?someinput=somevalue HTTP/1.1' . "\r\n"
. 'Host: ' . $host . "\r\n"
. 'Accept-Encoding: gzip, deflate' . "\r\n"
. 'User-Agent: Zend\Http\Client' . "\r\n"
. 'X-Powered-By: My Glorious Golden Ass' . "\r\n"
. 'Connection: close' . "\r\n\r\n",
$res->getBody()
);
}
/**
* Test that the proxy keys normalised by the client are correctly converted to what the proxy adapter expects.
*/
public function testProxyKeysCorrectlySetInProxyAdapter()
{
$adapterConfig = $this->_adapter->getConfig();
$adapterHost = $adapterConfig['proxy_host'];
$adapterPort = $adapterConfig['proxy_port'];
$this->assertSame($this->host, $adapterHost);
$this->assertSame($this->port, $adapterPort);
}
public function testProxyHasAllSocketConfigs()
{
$socket = new Socket();
$socketConfig = $socket->getConfig();
$proxy = new Proxy();
$proxyConfig = $proxy->getConfig();
foreach (array_keys($socketConfig) as $socketConfigKey) {
$this->assertArrayHasKey(
$socketConfigKey,
$proxyConfig,
'Proxy adapter should have all the Socket configuration keys'
);
}
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/TestAdapterTest.php | test/Client/TestAdapterTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
use PHPUnit\Framework\TestCase;
use Zend\Http\Client\Adapter\Exception\InvalidArgumentException;
use Zend\Http\Client\Adapter\Exception\OutOfRangeException;
use Zend\Http\Client\Adapter\Exception\RuntimeException;
use Zend\Http\Client\Adapter\Test;
use Zend\Http\Response;
/**
* Exercises Zend_Http_Client_Adapter_Test
*
* @group Zend_Http
* @group Zend_Http_Client
*/
class TestAdapterTest extends TestCase
{
/**
* Test adapter
*
* @var Test
*/
protected $adapter;
/**
* Set up the test adapter before running the test
*/
public function setUp()
{
$this->adapter = new Test();
}
/**
* Tear down the test adapter after running the test
*/
public function tearDown()
{
$this->adapter = null;
}
/**
* Make sure an exception is thrown on invalid configuration
*/
public function testSetConfigThrowsOnInvalidConfig()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Array or Traversable object expected');
$this->adapter->setOptions('foo');
}
public function testSetConfigReturnsQuietly()
{
$this->adapter->setOptions(['foo' => 'bar']);
}
public function testConnectReturnsQuietly()
{
$this->adapter->connect('http://foo');
}
public function testCloseReturnsQuietly()
{
$this->adapter->close();
}
public function testFailRequestOnDemand()
{
$this->adapter->setNextRequestWillFail(true);
try {
// Make a connection that will fail
$this->adapter->connect('http://foo');
$this->fail();
} catch (RuntimeException $e) {
// Connect again to see that the next request does not fail
$this->adapter->connect('http://foo');
}
}
public function testReadDefaultResponse()
{
$expected = "HTTP/1.1 400 Bad Request\r\n\r\n";
$this->assertEquals($expected, $this->adapter->read());
}
public function testReadingSingleResponse()
{
$expected = "HTTP/1.1 200 OK\r\n\r\n";
$this->adapter->setResponse($expected);
$this->assertEquals($expected, $this->adapter->read());
$this->assertEquals($expected, $this->adapter->read());
}
public function testReadingResponseCycles()
{
$expected = [
"HTTP/1.1 200 OK\r\n\r\n",
"HTTP/1.1 302 Moved Temporarily\r\n\r\n",
];
$this->adapter->setResponse($expected[0]);
$this->adapter->addResponse($expected[1]);
$this->assertEquals($expected[0], $this->adapter->read());
$this->assertEquals($expected[1], $this->adapter->read());
$this->assertEquals($expected[0], $this->adapter->read());
}
/**
* Test that responses could be added as strings
*
* @dataProvider validHttpResponseProvider
*
* @param string $testResponse
*/
public function testAddResponseAsString($testResponse)
{
$this->adapter->read(); // pop out first response
$this->adapter->addResponse($testResponse);
$this->assertEquals($testResponse, $this->adapter->read());
}
/**
* Test that responses could be added as objects (ZF-7009)
*
* @link http://framework.zend.com/issues/browse/ZF-7009
*
* @dataProvider validHttpResponseProvider
*
* @param string $testResponse
*/
public function testAddResponseAsObject($testResponse)
{
$this->adapter->read(); // pop out first response
$respObj = Response::fromString($testResponse);
$this->adapter->addResponse($respObj);
$this->assertEquals($testResponse, $this->adapter->read());
}
public function testReadingResponseCyclesWhenSetByArray()
{
$expected = [
"HTTP/1.1 200 OK\r\n\r\n",
"HTTP/1.1 302 Moved Temporarily\r\n\r\n",
];
$this->adapter->setResponse($expected);
$this->assertEquals($expected[0], $this->adapter->read());
$this->assertEquals($expected[1], $this->adapter->read());
$this->assertEquals($expected[0], $this->adapter->read());
}
public function testSettingNextResponseByIndex()
{
$expected = [
"HTTP/1.1 200 OK\r\n\r\n",
"HTTP/1.1 302 Moved Temporarily\r\n\r\n",
"HTTP/1.1 404 Not Found\r\n\r\n",
];
$this->adapter->setResponse($expected);
$this->assertEquals($expected[0], $this->adapter->read());
foreach ($expected as $i => $expected) {
$this->adapter->setResponseIndex($i);
$this->assertEquals($expected, $this->adapter->read());
}
}
public function testSettingNextResponseToAnInvalidIndex()
{
$indexes = [-1, 1];
foreach ($indexes as $i) {
try {
$this->adapter->setResponseIndex($i);
$this->fail();
} catch (\Exception $e) {
$this->assertInstanceOf(OutOfRangeException::class, $e);
$this->assertRegexp('/out of range/i', $e->getMessage());
}
}
}
/**
* Data Providers
*/
/**
* Provide valid HTTP responses as string
*
* @return array
*/
public static function validHttpResponseProvider()
{
return [
['HTTP/1.1 200 OK' . "\r\n\r\n"],
[
'HTTP/1.1 302 Moved Temporarily' . "\r\n"
. 'Location: http://example.com/baz' . "\r\n\r\n",
],
[
'HTTP/1.1 404 Not Found' . "\r\n"
. 'Date: Sun, 14 Jun 2009 10:40:06 GMT' . "\r\n"
. 'Server: Apache/2.2.3 (CentOS)' . "\r\n"
. 'Content-Length: 281' . "\r\n"
. 'Connection: close' . "\r\n"
. 'Content-Type: text/html; charset=iso-8859-1' . "\r\n\r\n"
. '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">' . "\n"
. '<html><head>' . "\n"
. '<title>404 Not Found</title>' . "\n"
. '</head><body>' . "\n"
. '<h1>Not Found</h1>' . "\n"
. '<p>The requested URL /foo/bar was not found on this server.</p>' . "\n"
. '<hr>' . "\n"
. '<address>Apache/2.2.3 (CentOS) Server at example.com Port 80</address>' . "\n"
. '</body></html>',
],
];
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/UseCaseTest.php | test/Client/UseCaseTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
use PHPUnit\Framework\TestCase;
use Zend\Http\Client as HTTPClient;
use Zend\Http\Client\Adapter\AdapterInterface;
use Zend\Http\Client\Adapter\Socket;
use Zend\Http\Request;
/**
* This are the test for the prototype of Zend\Http\Client
*
* @group Zend_Http
* @group Zend_Http_Client
*/
class UseCaseTest extends TestCase
{
/**
* The bast URI for this test, containing all files in the files directory
* Should be set in phpunit.xml or phpunit.xml.dist
*
* @var string
*/
protected $baseuri;
/**
* Common HTTP client
*
* @var HTTPClient
*/
protected $client;
/**
* Common HTTP client adapter
*
* @var AdapterInterface
*/
protected $adapter;
/**
* Configuration array
*
* @var array
*/
protected $config = [
'adapter' => Socket::class,
];
/**
* Set up the test case
*/
protected function setUp()
{
if (getenv('TESTS_ZEND_HTTP_CLIENT_BASEURI')
&& (filter_var(getenv('TESTS_ZEND_HTTP_CLIENT_BASEURI'), FILTER_VALIDATE_BOOLEAN) != false)
) {
$this->baseuri = getenv('TESTS_ZEND_HTTP_CLIENT_BASEURI');
$this->client = new HTTPClient($this->baseuri);
} else {
// Skip tests
$this->markTestSkipped(sprintf(
'%s dynamic tests are not enabled in phpunit.xml',
HTTPClient::class
));
}
}
/**
* Clean up the test environment
*/
protected function tearDown()
{
$this->client = null;
}
public function testHttpGet()
{
$this->client->setMethod(Request::METHOD_GET);
$response = $this->client->send();
$this->assertTrue($response->isSuccess());
}
public function testStaticHttpGet()
{
// $response= HTTPClient::get($this->baseuri);
// $this->assertTrue($response->isSuccess());
}
public function testRequestHttpGet()
{
$client = new HTTPClient();
$request = new Request();
$request->setUri($this->baseuri);
$request->setMethod(Request::METHOD_GET);
$response = $client->send($request);
$this->assertTrue($response->isSuccess());
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/SocketTest.php | test/Client/SocketTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
use stdClass;
use Zend\Config\Config;
use Zend\Http\Client\Adapter;
use Zend\Http\Client\Adapter\Exception\InvalidArgumentException;
use Zend\Http\Client\Adapter\Exception\RuntimeException;
use Zend\Http\Client\Adapter\Socket;
use Zend\Uri\Uri;
/**
* This Testsuite includes all Zend_Http_Client that require a working web
* server to perform. It was designed to be extendable, so that several
* test suites could be run against several servers, with different client
* adapters and configurations.
*
* Note that $this->baseuri must point to a directory on a web server
* containing all the files under the files directory. You should symlink
* or copy these files and set 'baseuri' properly.
*
* You can also set the proper constant in your test configuration file to
* point to the right place.
*
* @group Zend_Http
* @group Zend_Http_Client
*/
class SocketTest extends CommonHttpTests
{
/**
* Configuration array
*
* @var array
*/
protected $config = [
'adapter' => Socket::class,
];
/**
* Off-line common adapter tests
*/
/**
* Test that we can set a valid configuration array with some options
* @group ZHC001
*/
public function testConfigSetAsArray()
{
$config = [
'timeout' => 500,
'someoption' => 'hasvalue',
];
$this->_adapter->setOptions($config);
$hasConfig = $this->_adapter->getConfig();
foreach ($config as $k => $v) {
$this->assertEquals($v, $hasConfig[$k]);
}
}
public function testDefaultConfig()
{
$config = $this->_adapter->getConfig();
$this->assertEquals(true, $config['sslverifypeer']);
$this->assertEquals(false, $config['sslallowselfsigned']);
$this->assertEquals(true, $config['sslverifypeername']);
}
public function testConnectingViaSslEnforcesDefaultSslOptionsOnContext()
{
$config = ['timeout' => 30];
$this->_adapter->setOptions($config);
try {
$this->_adapter->connect('localhost', 443, true);
} catch (RuntimeException $e) {
// Test is designed to allow connect failure because we're interested
// only in the stream context state created within that method.
}
$context = $this->_adapter->getStreamContext();
$options = stream_context_get_options($context);
$this->assertTrue($options['ssl']['verify_peer']);
$this->assertFalse($options['ssl']['allow_self_signed']);
$this->assertTrue($options['ssl']['verify_peer_name']);
}
public function testConnectingViaSslWithCustomSslOptionsOnContext()
{
$config = [
'timeout' => 30,
'sslverifypeer' => false,
'sslallowselfsigned' => true,
'sslverifypeername' => false,
];
$this->_adapter->setOptions($config);
try {
$this->_adapter->connect('localhost', 443, true);
} catch (RuntimeException $e) {
// Test is designed to allow connect failure because we're interested
// only in the stream context state created within that method.
}
$context = $this->_adapter->getStreamContext();
$options = stream_context_get_options($context);
$this->assertFalse($options['ssl']['verify_peer']);
$this->assertTrue($options['ssl']['allow_self_signed']);
$this->assertFalse($options['ssl']['verify_peer_name']);
}
/**
* Test Certificate File Option
* The configuration is set to a legitimate certificate bundle file,
* to exclude errors from being thrown from an invalid cafile context being set.
*/
public function testConnectingViaSslUsesCertificateFileContext()
{
$config = [
'timeout' => 30,
'sslcafile' => __DIR__ . '/_files/ca-bundle.crt',
];
$this->_adapter->setOptions($config);
try {
$this->_adapter->connect('localhost', 443, true);
} catch (RuntimeException $e) {
// Test is designed to allow connect failure because we're interested
// only in the stream context state created within that method.
}
$context = $this->_adapter->getStreamContext();
$options = stream_context_get_options($context);
$this->assertEquals($config['sslcafile'], $options['ssl']['cafile']);
}
/**
* Test that a Zend\Config object can be used to set configuration
*
* @link http://framework.zend.com/issues/browse/ZF-5577
*/
public function testConfigSetAsZendConfig()
{
$config = new Config([
'timeout' => 400,
'nested' => [
'item' => 'value',
],
]);
$this->_adapter->setOptions($config);
$hasConfig = $this->_adapter->getConfig();
$this->assertEquals($config->timeout, $hasConfig['timeout']);
$this->assertEquals($config->nested->item, $hasConfig['nested']['item']);
}
/**
* Check that an exception is thrown when trying to set invalid config
*
* @dataProvider invalidConfigProvider
*
* @param mixed $config
*/
public function testSetConfigInvalidConfig($config)
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Array or Zend\Config object expected');
$this->_adapter->setOptions($config);
}
public function provideValidTimeoutConfig()
{
return [
'integer' => [10],
'numeric' => ['10'],
];
}
/**
* @dataProvider provideValidTimeoutConfig
*/
public function testPassValidTimeout($timeout)
{
$adapter = new Adapter\Socket();
$adapter->setOptions(['timeout' => $timeout]);
$adapter->connect('framework.zend.com');
}
public function testThrowInvalidArgumentExceptionOnNonIntegerAndNonNumericStringTimeout()
{
$adapter = new Adapter\Socket();
$adapter->setOptions(['timeout' => 'timeout']);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('integer or numeric string expected, got string');
$adapter->connect('framework.zend.com');
}
/**
* Stream context related tests
*/
public function testGetNewStreamContext()
{
$adapterClass = $this->config['adapter'];
$adapter = new $adapterClass();
$context = $adapter->getStreamContext();
$this->assertEquals('stream-context', get_resource_type($context));
}
public function testSetNewStreamContextResource()
{
$adapterClass = $this->config['adapter'];
$adapter = new $adapterClass();
$context = stream_context_create();
$adapter->setStreamContext($context);
$this->assertEquals($context, $adapter->getStreamContext());
}
public function testSetNewStreamContextOptions()
{
$adapterClass = $this->config['adapter'];
$adapter = new $adapterClass();
$options = [
'socket' => [
'bindto' => '1.2.3.4:0',
],
'ssl' => [
'capath' => null,
'verify_peer' => true,
'allow_self_signed' => false,
'verify_peer_name' => true,
],
];
$adapter->setStreamContext($options);
$this->assertEquals($options, stream_context_get_options($adapter->getStreamContext()));
}
/**
* Test that setting invalid options / context causes an exception
*
* @dataProvider invalidContextProvider
*
* @param mixed $invalid
*/
public function testSetInvalidContextOptions($invalid)
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expecting either a stream context resource or array');
$adapterClass = $this->config['adapter'];
$adapter = new $adapterClass();
$adapter->setStreamContext($invalid);
}
public function testSetHttpsStreamContextParam()
{
if ($this->client->getUri()->getScheme() != 'https') {
$this->markTestSkipped();
}
$adapterClass = $this->config['adapter'];
$adapter = new $adapterClass();
$adapter->setStreamContext([
'ssl' => [
'capture_peer_cert' => true,
'capture_peer_chain' => true,
],
]);
$this->client->setAdapter($adapter);
$this->client->setUri($this->baseuri . '/testSimpleRequests.php');
$this->client->request();
$opts = stream_context_get_options($adapter->getStreamContext());
$this->assertTrue(isset($opts['ssl']['peer_certificate']));
}
/**
* Test that we get the right exception after a socket timeout
*
* @link http://framework.zend.com/issues/browse/ZF-7309
*/
public function testExceptionOnReadTimeout()
{
// Set 1 second timeout
$this->client->setOptions(['timeout' => 1]);
$start = microtime(true);
try {
$this->client->send();
$this->fail('Expected a timeout Zend\Http\Client\Adapter\Exception\TimeoutException');
} catch (Adapter\Exception\TimeoutException $e) {
$this->assertEquals(Adapter\Exception\TimeoutException::READ_TIMEOUT, $e->getCode());
}
$time = (microtime(true) - $start);
// We should be very close to 1 second
$this->assertLessThan(2, $time);
}
/**
* Test that a chunked response with multibyte characters is properly read
*
* This can fail in various PHP environments - for example, when mbstring
* overloads substr() and strlen(), and mbstring's internal encoding is
* not a single-byte encoding.
*
* @link http://framework.zend.com/issues/browse/ZF-6218
*/
public function testMultibyteChunkedResponseZF6218()
{
$md5 = '7667818873302f9995be3798d503d8d3';
$response = $this->client->send();
$this->assertEquals($md5, md5($response->getBody()));
}
/**
* Verifies that writing on a socket is considered valid even if 0 bytes
* were written.
*
* @runInSeparateProcess
*/
public function testAllowsZeroWrittenBytes()
{
$this->_adapter->connect('localhost');
require_once __DIR__ . '/_files/fwrite.php';
$this->_adapter->write('GET', new Uri('tcp://localhost:80/'), '1.1', [], 'test body');
}
/**
* Verifies that the headers are being set as given without changing any
* character case.
*/
public function testCaseInsensitiveHeaders()
{
$this->_adapter->connect('localhost');
$requestString = $this->_adapter->write(
'GET',
new Uri('tcp://localhost:80/'),
'1.1',
['x-test-header' => 'someTestHeader'],
'someTestBody'
);
$this->assertContains('x-test-header', $requestString);
}
/**
* Data Providers
*/
/**
* Provide invalid context resources / options
*
* @return array
*/
public static function invalidContextProvider()
{
return [
[new stdClass()],
[fopen('data://text/plain,', 'r')],
[false],
[null],
];
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/StaticClientTest.php | test/Client/StaticClientTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use Zend\Http\Client;
use Zend\Http\ClientStatic as HTTPClient;
/**
* This are the test for the prototype of Zend\Http\Client
*
* @group Zend\Http
* @group Zend\Http\Client
*/
class StaticClientTest extends TestCase
{
/**
* Uri for test
*
* @var string
*/
protected $baseuri;
/**
* Set up the test case
*/
protected function setUp()
{
if (getenv('TESTS_ZEND_HTTP_CLIENT_BASEURI')
&& (filter_var(getenv('TESTS_ZEND_HTTP_CLIENT_BASEURI'), FILTER_VALIDATE_BOOLEAN) != false)) {
$this->baseuri = getenv('TESTS_ZEND_HTTP_CLIENT_BASEURI');
if (substr($this->baseuri, -1) != '/') {
$this->baseuri .= '/';
}
} else {
// Skip tests
$this->markTestSkipped(sprintf(
'%s dynamic tests are not enabled in phpunit.xml',
HTTPClient::class
));
}
}
/**
* Test simple GET
*/
public function testHttpSimpleGet()
{
$response = HTTPClient::get($this->baseuri . 'testSimpleRequests.php');
$this->assertTrue($response->isSuccess());
}
/**
* Test GET with query string in URI
*/
public function testHttpGetWithParamsInUri()
{
$response = HTTPClient::get($this->baseuri . 'testGetData.php?foo');
$this->assertTrue($response->isSuccess());
$this->assertContains('foo', $response->getBody());
}
/**
* Test GET with query as params
*/
public function testHttpMultiGetWithParam()
{
$response = HTTPClient::get($this->baseuri . 'testGetData.php', ['foo' => 'bar']);
$this->assertTrue($response->isSuccess());
$this->assertContains('foo', $response->getBody());
$this->assertContains('bar', $response->getBody());
}
/**
* Test GET with body
*/
public function testHttpGetWithBody()
{
$getBody = 'baz';
$response = HTTPClient::get(
$this->baseuri . 'testRawGetData.php',
['foo' => 'bar'],
[],
$getBody
);
$this->assertTrue($response->isSuccess());
$this->assertContains('foo', $response->getBody());
$this->assertContains('bar', $response->getBody());
$this->assertContains($getBody, $response->getBody());
}
/**
* Test simple POST
*/
public function testHttpSimplePost()
{
$response = HTTPClient::post($this->baseuri . 'testPostData.php', ['foo' => 'bar']);
$this->assertTrue($response->isSuccess());
$this->assertContains('foo', $response->getBody());
$this->assertContains('bar', $response->getBody());
}
/**
* Test POST with header Content-Type
*/
public function testHttpPostContentType()
{
$response = HTTPClient::post(
$this->baseuri . 'testPostData.php',
['foo' => 'bar'],
['Content-Type' => Client::ENC_URLENCODED]
);
$this->assertTrue($response->isSuccess());
$this->assertContains('foo', $response->getBody());
$this->assertContains('bar', $response->getBody());
}
/**
* Test POST with body
*/
public function testHttpPostWithBody()
{
$postBody = 'foo';
$response = HTTPClient::post(
$this->baseuri . 'testRawPostData.php',
['foo' => 'bar'],
['Content-Type' => Client::ENC_URLENCODED],
$postBody
);
$this->assertTrue($response->isSuccess());
$this->assertContains($postBody, $response->getBody());
}
/**
* Test GET with adapter configuration
*
* @link https://github.com/zendframework/zf2/issues/6482
*/
public function testHttpGetUsesAdapterConfig()
{
$testUri = $this->baseuri . 'testSimpleRequests.php';
$config = [
'useragent' => 'simplegettest',
];
HTTPClient::get($testUri, [], [], null, $config);
$reflectedClass = new ReflectionClass(HTTPClient::class);
$property = $reflectedClass->getProperty('client');
$property->setAccessible(true);
$client = $property->getValue();
$rawRequest = $client->getLastRawRequest();
$this->assertContains('User-Agent: simplegettest', $rawRequest);
}
/**
* Test POST with adapter configuration
*
* @link https://github.com/zendframework/zf2/issues/6482
*/
public function testHttpPostUsesAdapterConfig()
{
$testUri = $this->baseuri . 'testPostData.php';
$config = [
'useragent' => 'simpleposttest',
];
HTTPClient::post($testUri, ['foo' => 'bar'], [], null, $config);
$reflectedClass = new ReflectionClass(HTTPClient::class);
$property = $reflectedClass->getProperty('client');
$property->setAccessible(true);
$client = $property->getValue();
$rawRequest = $client->getLastRawRequest();
$this->assertContains('User-Agent: simpleposttest', $rawRequest);
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/SocketKeepaliveTest.php | test/Client/SocketKeepaliveTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
/**
* This Testsuite includes all Zend_Http_Client that require a working web
* server to perform. It was designed to be extendable, so that several
* test suites could be run against several servers, with different client
* adapters and configurations.
*
* Note that $this->baseuri must point to a directory on a web server
* containing all the files under the files directory. You should symlink
* or copy these files and set 'baseuri' properly.
*
* You can also set the proper constand in your test configuration file to
* point to the right place.
*
* @group Zend_Http
* @group Zend_Http_Client
*/
use Zend\Http\Client\Adapter\Socket;
class SocketKeepaliveTest extends SocketTest
{
/**
* Configuration array
*
* @var array
*/
protected $config = [
'adapter' => Socket::class,
'keepalive' => true,
];
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/StaticTest.php | test/Client/StaticTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
use PHPUnit\Framework\TestCase;
use stdClass;
use Zend\Config\Config;
use Zend\Http\Client as HTTPClient;
use Zend\Http\Client\Adapter\Exception as ClientAdapterException;
use Zend\Http\Client\Adapter\Test;
use Zend\Http\Client\Exception as ClientException;
use Zend\Http\Exception\InvalidArgumentException;
use Zend\Http\Exception\RuntimeException;
use Zend\Http\Header\SetCookie;
use Zend\Uri\Http as UriHttp;
use ZendTest\Http\Client\TestAsset\MockAdapter;
use ZendTest\Http\Client\TestAsset\MockClient;
/**
* This Testsuite includes all Zend_Http_Client tests that do not rely
* on performing actual requests to an HTTP server. These tests can be
* executed once, and do not need to be tested with different servers /
* client setups.
*
* @group Zend_Http
* @group Zend_Http_Client
*/
class StaticTest extends TestCase
{
// @codingStandardsIgnoreStart
/**
* Common HTTP client
*
* @var HTTPClient
*/
protected $_client;
// @codingStandardsIgnoreEnd
/**
* Set up the test suite before each test
*/
public function setUp()
{
$this->_client = new MockClient('http://www.example.com');
}
/**
* Clean up after running a test
*/
public function tearDown()
{
$this->_client = null;
}
/**
* URI Tests
*/
/**
* Test we can SET and GET a URI as string
*/
public function testSetGetUriString()
{
$uristr = 'http://www.zend.com:80/';
$this->_client->setUri($uristr);
$uri = $this->_client->getUri();
$this->assertInstanceOf(UriHttp::class, $uri, 'Returned value is not a Uri object as expected');
$this->assertEquals($uri->__toString(), $uristr, 'Returned Uri object does not hold the expected URI');
$uri = $this->_client->getUri()->toString();
$this->assertInternalType(
'string',
$uri,
'Returned value expected to be a string, ' . gettype($uri) . ' returned'
);
$this->assertEquals($uri, $uristr, 'Returned string is not the expected URI');
}
/**
* Test we can SET and GET a URI as object
*/
public function testSetGetUriObject()
{
$uriobj = new UriHttp('http://www.zend.com:80/');
$this->_client->setUri($uriobj);
$uri = $this->_client->getUri();
$this->assertInstanceOf(UriHttp::class, $uri, 'Returned value is not a Uri object as expected');
$this->assertEquals($uri, $uriobj, 'Returned object is not the excepted Uri object');
}
/**
* Test that setting the same parameter twice in the query string does not
* get reduced to a single value only.
*/
public function testDoubleGetParameter()
{
$qstr = 'foo=bar&foo=baz';
$this->_client->setUri('http://example.com/test/?' . $qstr);
$this->_client->setAdapter(Test::class);
$this->_client->setMethod('GET');
$this->_client->send();
$this->assertContains(
$qstr,
$this->_client->getLastRawRequest(),
'Request is expected to contain the entire query string'
);
}
/**
* Header Tests
*/
/**
* Test we can get already set headers
*/
public function testGetHeader()
{
$this->_client->setHeaders([
'Accept-encoding' => 'gzip,deflate',
'Accept-language' => 'en,de,*',
]);
$this->assertEquals(
$this->_client->getHeader('Accept-encoding'),
'gzip, deflate',
'Returned value of header is not as expected'
);
$this->assertEquals(
$this->_client->getHeader('X-Fake-Header'),
null,
'Non-existing header should not return a value'
);
}
/**
* Authentication tests
*/
/**
* Test setAuth (dynamic method) fails when trying to use an unsupported
* authentication scheme
*/
public function testExceptUnsupportedAuthDynamic()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid or not supported authentication type: \'SuperStrongAlgo\'');
$this->_client->setAuth('shahar', '1234', 'SuperStrongAlgo');
}
/**
* Cookie and Cookie Jar tests
*/
/**
* Test we can properly set a new cookies
*/
public function testSetNewCookies()
{
$this->_client->addCookie('cookie', 'value');
$this->_client->addCookie('chocolate', 'chips');
$cookies = $this->_client->getCookies();
// Check we got the right cookiejar
$this->assertInternalType('array', $cookies);
$this->assertContainsOnlyInstancesOf(SetCookie::class, $cookies);
$this->assertCount(2, $cookies);
}
/**
* Test we can unset a cookie jar
*/
public function testUnsetCookies()
{
// Set the cookie jar just like in testSetNewCookieJar
$this->_client->addCookie('cookie', 'value');
$this->_client->addCookie('chocolate', 'chips');
$cookies = $this->_client->getCookies();
// Try unsetting the cookies
$this->_client->clearCookies();
$cookies = $this->_client->getCookies();
$this->assertEquals([], $cookies, 'Cookies are expected to be an empty array but it is not');
}
/**
* Make sure using an invalid cookie jar object throws an exception
*/
public function testSetInvalidCookies()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid parameter type passed as Cookie');
$this->_client->addCookie('cookie');
}
/**
* Configuration Handling
*/
/**
* Test that we can set a valid configuration array with some options
*/
public function testConfigSetAsArray()
{
$config = [
'timeout' => 500,
'someoption' => 'hasvalue',
];
$this->_client->setOptions($config);
$hasConfig = $this->_client->config;
foreach ($config as $k => $v) {
$this->assertEquals($v, $hasConfig[$k]);
}
}
/**
* Test that a Zend_Config object can be used to set configuration
*
* @link http://framework.zend.com/issues/browse/ZF-5577
*/
public function testConfigSetAsZendConfig()
{
$config = new Config([
'timeout' => 400,
'nested' => [
'item' => 'value',
],
]);
$this->_client->setOptions($config);
$hasConfig = $this->_client->config;
$this->assertEquals($config->timeout, $hasConfig['timeout']);
$this->assertEquals($config->nested->item, $hasConfig['nested']['item']);
}
/**
* Test that passing invalid variables to setConfig() causes an exception
*
* @dataProvider invalidConfigProvider
*
* @param mixed $config
*/
public function testConfigSetInvalid($config)
{
$this->expectException(ClientException\InvalidArgumentException::class);
$this->expectExceptionMessage('Config parameter is not valid');
$this->_client->setOptions($config);
}
/**
* Test that configuration options are passed to the adapter after the
* adapter is instantiated
*
* @group ZF-4557
*/
public function testConfigPassToAdapterZF4557()
{
$adapter = new MockAdapter();
// test that config passes when we set the adapter
$this->_client->setOptions(['param' => 'value1']);
$this->_client->setAdapter($adapter);
$adapterCfg = $adapter->config;
$this->assertEquals('value1', $adapterCfg['param']);
// test that adapter config value changes when we set client config
$this->_client->setOptions(['param' => 'value2']);
$adapterCfg = $adapter->config;
$this->assertEquals('value2', $adapterCfg['param']);
}
/**
* Other Tests
*/
/**
* Test the getLastRawResponse() method actually returns the last response
*/
public function testGetLastRawResponse()
{
// First, make sure we get null before the request
$this->assertEquals(
null,
$this->_client->getLastRawResponse(),
'getLastRawResponse() is still expected to return null'
);
// Now, test we get a proper response after the request
$this->_client->setUri('http://example.com/foo/bar');
$this->_client->setAdapter(Test::class);
$response = $this->_client->send();
$this->assertSame(
$response,
$this->_client->getResponse(),
'Response is expected to be identical to the result of getResponse()'
);
}
/**
* Test that getLastRawResponse returns null when not storing
*/
public function testGetLastRawResponseWhenNotStoring()
{
// Now, test we get a proper response after the request
$this->_client->setUri('http://example.com/foo/bar');
$this->_client->setAdapter(Test::class);
$this->_client->setOptions(['storeresponse' => false]);
$this->_client->send();
$this->assertNull(
$this->_client->getLastRawResponse(),
'getLastRawResponse is expected to be null when not storing'
);
}
/**
* Check we get an exception when trying to send a POST request with an
* invalid content-type header
*/
public function testInvalidPostContentType()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Cannot handle content type \'x-foo/something-fake\' automatically');
$this->_client->setEncType('x-foo/something-fake');
$this->_client->setParameterPost(['parameter' => 'value']);
$this->_client->setMethod('POST');
// This should throw an exception
$this->_client->send();
}
/**
* Check we get an exception if there's an error in the socket
*/
public function testSocketErrorException()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->expectException(ClientAdapterException\RuntimeException::class);
$this->expectExceptionMessage('Unable to connect to 255.255.255.255:80');
// Try to connect to an invalid host
$this->_client->setUri('http://255.255.255.255');
// Reduce timeout to 3 seconds to avoid waiting
$this->_client->setOptions(['timeout' => 3]);
// This call should cause an exception
$this->_client->send();
}
/**
* Check that an exception is thrown if non-word characters are used in
* the request method.
*
* @dataProvider invalidMethodProvider
*
* @param string $method
*/
public function testSettingInvalidMethodThrowsException($method)
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid HTTP method passed');
$this->_client->setMethod($method);
}
/**
* Test that POST data with multi-dimentional array is properly encoded as
* multipart/form-data
*/
public function testFormDataEncodingWithMultiArrayZF7038()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->_client->setAdapter(Test::class);
$this->_client->setUri('http://example.com');
$this->_client->setEncType(HTTPClient::ENC_FORMDATA);
$this->_client->setParameterPost([
'test' => [
'v0.1',
'v0.2',
'k1' => 'v1.0',
'k2' => [
'v2.1',
'k2.1' => 'v2.1.0',
],
],
]);
$this->_client->setMethod('POST');
$this->_client->send();
$expectedLines = file(__DIR__ . '/_files/ZF7038-multipartarrayrequest.txt');
$gotLines = explode("\n", $this->_client->getLastRawRequest());
$this->assertEquals(count($expectedLines), count($gotLines));
while (($expected = array_shift($expectedLines))
&& ($got = array_shift($gotLines))
) {
$expected = trim($expected);
$got = trim($got);
$this->assertRegExp(sprintf('/^%s$/', $expected), $got);
}
}
/**
* Test that we properly calculate the content-length of multibyte-encoded
* request body
*
* This may file in case that mbstring overloads the substr and strlen
* functions, and the mbstring internal encoding is a multibyte encoding.
*
* @link http://framework.zend.com/issues/browse/ZF-2098
*/
public function testMultibyteRawPostDataZF2098()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->_client->setAdapter(Test::class);
$this->_client->setUri('http://example.com');
$bodyFile = __DIR__ . '/_files/ZF2098-multibytepostdata.txt';
$this->_client->setRawBody(file_get_contents($bodyFile));
$this->_client->setEncType('text/plain');
$this->_client->setMethod('POST');
$this->_client->send();
$request = $this->_client->getLastRawRequest();
if (! preg_match('/^content-length:\s+(\d+)/mi', $request, $match)) {
$this->fail('Unable to find content-length header in request');
}
$this->assertEquals(filesize($bodyFile), (int) $match[1]);
}
/**
* Testing if the connection isn't closed
*
* @group ZF-9685
*/
public function testOpenTempStreamWithValidFileDoesntThrowsException()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$url = 'http://www.example.com/';
$config = [
'outputstream' => realpath(__DIR__ . '/_files/zend_http_client_stream.file'),
];
$client = new HTTPClient($url, $config);
$result = $client->send();
// we can safely return until we can verify link is still active
// @todo verify link is still active
}
/**
* Test if a downloaded file can be deleted
*
* @group ZF-9685
*/
public function testDownloadedFileCanBeDeleted()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped('Zend\Http\Client online tests are not enabled');
}
$url = 'http://www.example.com/';
$outputFile = @tempnam(@sys_get_temp_dir(), 'zht');
if (! is_file($outputFile)) {
$this->markTestSkipped('Failed to create a temporary file');
}
$config = [
'outputstream' => $outputFile,
];
$client = new HTTPClient($url, $config);
$result = $client->send();
$this->assertInstanceOf('Zend\Http\Response\Stream', $result);
if (DIRECTORY_SEPARATOR === '\\') {
$this->assertFalse(@unlink($outputFile), 'Deleting an open file should fail on Windows');
}
fclose($result->getStream());
$this->assertTrue(@unlink($outputFile), 'Failed to delete downloaded file');
}
/**
* Testing if the connection can be closed
*
* @group ZF-9685
*/
public function testOpenTempStreamWithBogusFileClosesTheConnection()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$url = 'http://www.example.com';
$config = [
'outputstream' => '/path/to/bogus/file.ext',
];
$client = new HTTPClient($url, $config);
$client->setMethod('GET');
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Could not open temp file /path/to/bogus/file.ext');
$client->send();
}
/**
* Test sending cookie with encoded value
*
* @group fix-double-encoding-problem-about-cookie-value
*/
public function testEncodedCookiesInRequestHeaders()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->_client->addCookie('foo', 'bar=baz');
$this->_client->send();
$cookieValue = 'Cookie: foo=' . urlencode('bar=baz');
$this->assertContains(
$cookieValue,
$this->_client->getLastRawRequest(),
'Request is expected to contain the entire cookie "keyname=encoded_value"'
);
}
/**
* Test sending cookie header with raw value
*
* @group fix-double-encoding-problem-about-cookie-value
*/
public function testRawCookiesInRequestHeaders()
{
if (! getenv('TESTS_ZEND_HTTP_CLIENT_ONLINE')) {
$this->markTestSkipped(sprintf(
'%s online tests are not enabled',
HTTPClient::class
));
}
$this->_client->setOptions(['encodecookies' => false]);
$this->_client->addCookie('foo', 'bar=baz');
$this->_client->send();
$cookieValue = 'Cookie: foo=bar=baz';
$this->assertContains(
$cookieValue,
$this->_client->getLastRawRequest(),
'Request is expected to contain the entire cookie "keyname=raw_value"'
);
}
/**
* Data providers
*/
/**
* Data provider of valid non-standard HTTP methods
*
* @return array
*/
public static function validMethodProvider()
{
return [
['OPTIONS'],
['POST'],
['DOSOMETHING'],
['PROPFIND'],
['Some_Characters'],
['X-MS-ENUMATTS'],
];
}
/**
* Data provider of invalid HTTP methods
*
* @return array
*/
public static function invalidMethodProvider()
{
return [
['N@5TYM3T#0D'],
['TWO WORDS'],
['GET http://foo.com/?'],
['Injected' . "\n" . 'newline'],
];
}
/**
* Data provider for invalid configuration containers
*
* @return array
*/
public static function invalidConfigProvider()
{
return [
[false],
['foobar'],
['foo' => 'bar'],
[null],
[new stdClass()],
[55],
];
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/SocketPersistentTest.php | test/Client/SocketPersistentTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
/**
* This Testsuite includes all Zend_Http_Client that require a working web
* server to perform. It was designed to be extendable, so that several
* test suites could be run against several servers, with different client
* adapters and configurations.
*
* Note that $this->baseuri must point to a directory on a web server
* containing all the files under the files directory. You should symlink
* or copy these files and set 'baseuri' properly.
*
* You can also set the proper constand in your test configuration file to
* point to the right place.
*
* @group Zend_Http
* @group Zend_Http_Client
*/
use Zend\Http\Client\Adapter\Socket;
class SocketPersistentTest extends SocketTest
{
/**
* Configuration array
*
* @var array
*/
protected $config = [
'adapter' => Socket::class,
'persistent' => true,
'keepalive' => true,
];
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/CommonHttpTests.php | test/Client/CommonHttpTests.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
use Exception;
use PHPUnit\Framework\TestCase;
use stdClass;
use Zend\Http\Client as HTTPClient;
use Zend\Http\Client\Adapter;
use Zend\Http\Client\Adapter\AdapterInterface;
use Zend\Http\Client\Adapter\Exception as AdapterException;
use Zend\Http\Client\Adapter\Socket;
use Zend\Http\Request;
use Zend\Http\Response\Stream;
use Zend\Stdlib\Parameters;
/**
* This Testsuite includes all Zend_Http_Client that require a working web
* server to perform. It was designed to be extendable, so that several
* test suites could be run against several servers, with different client
* adapters and configurations.
*
* Note that $this->baseuri must point to a directory on a web server
* containing all the files under the files directory. You should symlink
* or copy these files and set 'baseuri' properly.
*
* You can also set the proper constant in your test configuration file to
* point to the right place.
*
* @group Zend_Http
* @group Zend_Http_Client
*/
abstract class CommonHttpTests extends TestCase
{
/**
* The bast URI for this test, containing all files in the files directory
* Should be set in phpunit.xml or phpunit.xml.dist
*
* @var string
*/
protected $baseuri;
/**
* Common HTTP client
*
* @var HTTPClient
*/
protected $client;
// @codingStandardsIgnoreStart
/**
* Common HTTP client adapter
*
* @var AdapterInterface
*/
protected $_adapter;
// @codingStandardsIgnoreEnd
/**
* Configuration array
*
* @var array
*/
protected $config = [
'adapter' => Socket::class,
];
/**
* Set up the test case
*/
protected function setUp()
{
$baseUri = getenv('TESTS_ZEND_HTTP_CLIENT_BASEURI');
if ($baseUri && filter_var($baseUri, FILTER_VALIDATE_URL) !== false) {
$this->baseuri = $baseUri;
if (substr($this->baseuri, -1) !== '/') {
$this->baseuri .= '/';
}
$name = $this->getName();
if (($pos = strpos($name, ' ')) !== false) {
$name = substr($name, 0, $pos);
}
$uri = $this->baseuri . $name . '.php';
$this->_adapter = new $this->config['adapter']();
$this->client = new HTTPClient($uri, $this->config);
$this->client->setAdapter($this->_adapter);
} else {
// Skip tests
$this->markTestSkipped(sprintf(
'%s dynamic tests are not enabled in phpunit.xml',
HTTPClient::class
));
}
}
/**
* Clean up the test environment
*/
protected function tearDown()
{
$this->client = null;
$this->_adapter = null;
}
/**
* Simple request tests
*/
public function methodProvider()
{
return [
[Request::METHOD_GET],
[Request::METHOD_POST],
[Request::METHOD_OPTIONS],
[Request::METHOD_PUT],
[Request::METHOD_DELETE],
[Request::METHOD_PATCH],
];
}
/**
* Test simple requests
*
* @dataProvider methodProvider
*
* @param string $method
*/
public function testSimpleRequests($method)
{
$this->client->setMethod($method);
$res = $this->client->send();
$this->assertTrue($res->isSuccess(), sprintf('HTTP %s request failed.', $method));
}
/**
* Test we can get the last request as string
*/
public function testGetLastRawRequest()
{
$this->client->setUri($this->baseuri . 'testHeaders.php');
$this->client->setParameterGet(['someinput' => 'somevalue']);
$this->client->setHeaders([
'X-Powered-By' => 'My Glorious Golden Ass',
]);
$this->client->setMethod('TRACE');
$res = $this->client->send();
if ($res->getStatusCode() == 405 || $res->getStatusCode() == 501) {
$this->markTestSkipped('Server does not allow the TRACE method');
}
$this->assertEquals(
$this->client->getLastRawRequest(),
$res->getBody(),
'Response body should be exactly like the last request'
);
}
/**
* GET and POST parameters tests
*/
/**
* Test we can properly send GET parameters
*
* @dataProvider parameterArrayProvider
*
* @param array $params
*/
public function testGetData(array $params)
{
$this->client->setUri($this->client->getUri() . '?name=Arthur');
$this->client->setParameterGet($params);
$res = $this->client->send();
$this->assertEquals(serialize(array_merge(['name' => 'Arthur'], $params)), $res->getBody());
}
/**
* Test we can properly send POST parameters with
* application/x-www-form-urlencoded content type
*
* @dataProvider parameterArrayProvider
*
* @param array $params
*/
public function testPostDataUrlEncoded(array $params)
{
$this->client->setUri($this->baseuri . 'testPostData.php');
$this->client->setEncType(HTTPClient::ENC_URLENCODED);
$this->client->setParameterPost($params);
$this->client->setMethod('POST');
$this->assertFalse($this->client->getRequest()->isPatch());
$res = $this->client->send();
$this->assertEquals(serialize($params), $res->getBody(), 'POST data integrity test failed');
}
/**
* Test we can properly send PATCH parameters with
* application/x-www-form-urlencoded content type
*
* @dataProvider parameterArrayProvider
*
* @param array $params
*/
public function testPatchData(array $params)
{
$client = $this->client;
$client->setUri($this->baseuri . 'testPatchData.php');
$client->setRawBody(serialize($params));
$client->setMethod('PATCH');
$this->assertEquals($client::ENC_URLENCODED, $this->client->getEncType());
$this->assertTrue($client->getRequest()->isPatch());
$res = $this->client->send();
$this->assertEquals(serialize($params), $res->getBody(), 'PATCH data integrity test failed');
}
/**
* Test we can properly send DELETE parameters with
* application/x-www-form-urlencoded content type
*
* @dataProvider parameterArrayProvider
*
* @param array $params
*/
public function testDeleteData(array $params)
{
$client = $this->client;
$client->setUri($this->baseuri . 'testDeleteData.php');
$client->setRawBody(serialize($params));
$client->setMethod('DELETE');
$this->assertEquals($client::ENC_URLENCODED, $this->client->getEncType());
$this->assertTrue($client->getRequest()->isDelete());
$res = $this->client->send();
$this->assertEquals(serialize($params), $res->getBody(), 'DELETE data integrity test failed');
}
/**
* Test we can properly send OPTIONS parameters with
* application/x-www-form-urlencoded content type
*
* @dataProvider parameterArrayProvider
*
* @param array $params
*/
public function testOptionsData(array $params)
{
$client = $this->client;
$client->setUri($this->baseuri . 'testOptionsData.php');
$client->setRawBody(serialize($params));
$client->setMethod('OPTIONS');
$this->assertEquals($client::ENC_URLENCODED, $this->client->getEncType());
$this->assertTrue($client->getRequest()->isOptions());
$res = $this->client->send();
$this->assertEquals(serialize($params), $res->getBody(), 'OPTIONS data integrity test failed');
}
/**
* Test we can properly send POST parameters with
* multipart/form-data content type
*
* @dataProvider parameterArrayProvider
*
* @param array $params
*/
public function testPostDataMultipart(array $params)
{
$this->client->setUri($this->baseuri . 'testPostData.php');
$this->client->setEncType(HTTPClient::ENC_FORMDATA);
$this->client->setParameterPost($params);
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertEquals(serialize($params), $res->getBody(), 'POST data integrity test failed');
}
/**
* Test using raw HTTP POST data
*/
public function testRawPostData()
{
$data = 'Chuck Norris never wet his bed as a child. The bed wet itself out of fear.';
$this->client->setRawBody($data);
$this->client->setEncType('text/html');
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertEquals($data, $res->getBody(), 'Response body does not contain the expected data');
}
/**
* Make sure we can reset the parameters between consecutive requests
*/
public function testResetParameters()
{
$params = [
'quest' => 'To seek the holy grail',
'YourMother' => 'Was a hamster',
'specialChars' => '<>$+ &?=[]^%',
'array' => ['firstItem', 'secondItem', '3rdItem'],
];
$headers = ['X-Foo' => 'bar'];
$this->client->setParameterPost($params);
$this->client->setParameterGet($params);
$this->client->setHeaders($headers);
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertContains(
serialize($params) . "\n" . serialize($params),
$res->getBody(),
'returned body does not contain all GET and POST parameters (it should!)'
);
$this->client->resetParameters();
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertNotContains(
serialize($params),
$res->getBody(),
"returned body contains GET or POST parameters (it shouldn't!)"
);
$headerXFoo = $this->client->getHeader('X-Foo');
$this->assertEmpty($headerXFoo, 'Header not preserved by reset');
}
/**
* Test parameters get reset when we unset them
*/
public function testParameterUnset()
{
$this->client->setUri($this->baseuri . 'testResetParameters.php');
$gparams = [
'cheese' => 'camambert',
'beer' => 'jever pilnsen',
];
$pparams = [
'from' => 'bob',
'to' => 'alice',
];
$this->client->setParameterGet($gparams)->setParameterPost($pparams);
// Remove some parameters
$this->client->setParameterGet(['cheese' => null])
->setParameterPost(['to' => null]);
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertNotContains('cheese', $res->getBody(), 'The "cheese" GET parameter was expected to be unset');
$this->assertNotContains('alice', $res->getBody(), 'The "to" POST parameter was expected to be unset');
}
/**
* Header Tests
*/
/**
* Make sure we can set a single header
*/
public function testHeadersSingle()
{
$this->client->setUri($this->baseuri . 'testHeaders.php');
$headers = [
'Accept-encoding' => 'gzip, deflate',
'X-baz' => 'Foo',
'X-powered-by' => 'A large wooden badger',
'Accept' => 'text/xml, text/html, */*',
];
$this->client->setHeaders($headers);
$this->client->setMethod('TRACE');
$res = $this->client->send();
if ($res->getStatusCode() == 405 || $res->getStatusCode() == 501) {
$this->markTestSkipped('Server does not allow the TRACE method');
}
$body = strtolower($res->getBody());
foreach ($headers as $key => $val) {
$this->assertContains(strtolower($key . ': ' . $val), $body);
}
}
/**
* Test we can set an array of headers
*/
public function testHeadersArray()
{
$this->client->setUri($this->baseuri . 'testHeaders.php');
$headers = [
'Accept-encoding' => 'gzip, deflate',
'X-baz' => 'Foo',
'X-powered-by' => 'A large wooden badger',
'Accept: text/xml, text/html, */*',
];
$this->client->setHeaders($headers);
$this->client->setMethod('TRACE');
$res = $this->client->send();
if ($res->getStatusCode() == 405 || $res->getStatusCode() == 501) {
$this->markTestSkipped('Server does not allow the TRACE method');
}
$body = strtolower($res->getBody());
foreach ($headers as $key => $val) {
if (is_string($key)) {
$this->assertContains(strtolower($key . ': ' . $val), $body);
} else {
$this->assertContains(strtolower($val), $body);
}
}
}
/**
* Test we can set a set of values for one header
*/
public function testMultipleHeader()
{
$this->client->setUri($this->baseuri . 'testHeaders.php');
$headers = [
'Accept-encoding' => 'gzip, deflate',
'X-baz' => 'Foo',
'X-powered-by' => [
'A large wooden badger',
'My Shiny Metal Ass',
'Dark Matter',
],
'Cookie' => [
'foo=bar',
'baz=waka',
],
];
$this->client->setHeaders($headers);
$this->client->setMethod('TRACE');
$res = $this->client->send();
if ($res->getStatusCode() == 405 || $res->getStatusCode() == 501) {
$this->markTestSkipped('Server does not allow the TRACE method');
}
$body = strtolower($res->getBody());
foreach ($headers as $key => $val) {
if (is_array($val)) {
$val = implode('; ', $val);
}
$this->assertContains(strtolower($key . ': ' . $val), $body);
}
}
/**
* Redirection tests
*/
/**
* Test the client properly redirects in default mode
*/
public function testRedirectDefault()
{
$this->client->setUri($this->baseuri . 'testRedirections.php');
// Set some parameters
$this->client->setParameterGet(['swallow' => 'african']);
$this->client->setParameterPost(['Camelot' => 'A silly place']);
// Request
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertEquals(3, $this->client->getRedirectionsCount(), 'Redirection counter is not as expected');
// Make sure the body does *not* contain the set parameters
$this->assertNotContains('swallow', $res->getBody());
$this->assertNotContains('Camelot', $res->getBody());
}
/**
* @group ZF-4136
* @link http://framework.zend.com/issues/browse/ZF2-122
*/
public function testRedirectPersistsCookies()
{
$this->client->setUri($this->baseuri . 'testRedirections.php');
// Set some parameters
$this->client->setParameterGet(['swallow' => 'african']);
$this->client->setParameterPost(['Camelot' => 'A silly place']);
// Send POST request
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertEquals(3, $this->client->getRedirectionsCount(), 'Redirection counter is not as expected');
// Make sure the body does *not* contain the set parameters
$this->assertNotContains('swallow', $res->getBody());
$this->assertNotContains('Camelot', $res->getBody());
// Check that we have received and persisted expected cookies
$cookies = $this->client->getCookies();
$this->assertInternalType('array', $cookies, 'Client is not sending cookies on redirect');
$this->assertArrayHasKey('zf2testSessionCookie', $cookies, 'Client is not sending cookies on redirect');
$this->assertArrayHasKey('zf2testLongLivedCookie', $cookies, 'Client is not sending cookies on redirect');
$this->assertEquals('positive', $cookies['zf2testSessionCookie']->getValue());
$this->assertEquals('positive', $cookies['zf2testLongLivedCookie']->getValue());
// Check that expired cookies are not passed on
$this->assertArrayNotHasKey('zf2testExpiredCookie', $cookies, 'Expired cookies are not removed.');
}
/**
* Make sure the client properly redirects in strict mode
*/
public function testRedirectStrict()
{
$this->client->setUri($this->baseuri . 'testRedirections.php');
// Set some parameters
$this->client->setParameterGet(['swallow' => 'african']);
$this->client->setParameterPost(['Camelot' => 'A silly place']);
// Set strict redirections
$this->client->setOptions(['strictredirects' => true]);
// Request
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertEquals(3, $this->client->getRedirectionsCount(), 'Redirection counter is not as expected');
// Make sure the body *does* contain the set parameters
$this->assertContains('swallow', $res->getBody());
$this->assertContains('Camelot', $res->getBody());
}
/**
* Make sure redirections stop when limit is exceeded
*/
public function testMaxRedirectsExceeded()
{
$this->client->setUri($this->baseuri . 'testRedirections.php');
// Set some parameters
$this->client->setParameterGet(['swallow' => 'african']);
$this->client->setParameterPost(['Camelot' => 'A silly place']);
// Set lower max redirections
// Try with strict redirections first
$this->client->setOptions(['strictredirects' => true, 'maxredirects' => 2]);
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertTrue(
$res->isRedirect(),
sprintf(
'Last response was not a redirection as expected. Response code: %d. '
. 'Redirections counter: %d (when strict redirects are on)',
$res->getStatusCode(),
$this->client->getRedirectionsCount()
)
);
// Then try with normal redirections
$this->client->setParameterGet(['redirection' => '0']);
$this->client->setOptions(['strictredirects' => false]);
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertTrue(
$res->isRedirect(),
sprintf(
'Last response was not a redirection as expected. Response code: %d.'
. ' Redirections counter: %d (when strict redirects are off)',
$res->getStatusCode(),
$this->client->getRedirectionsCount()
)
);
}
/**
* Test we can properly redirect to an absolute path (not full URI)
*/
public function testAbsolutePathRedirect()
{
$this->client->setUri($this->baseuri . 'testRelativeRedirections.php');
$this->client->setParameterGet(['redirect' => 'abpath']);
$this->client->setOptions(['maxredirects' => 1]);
// Get the host and port part of our baseuri
$port = $this->client->getUri()->getPort() == 80 ? '' : ':' . $this->client->getUri()->getPort();
$uri = $this->client->getUri()->getScheme() . '://' . $this->client->getUri()->getHost() . $port;
$res = $this->client->send();
$this->assertEquals(
sprintf('%s/path/to/fake/file.ext?redirect=abpath', $uri),
$this->client->getUri()->toString(),
sprintf('The new location is not as expected: %s', $this->client->getUri()->toString())
);
}
/**
* Test we can properly redirect to a relative path
*/
public function testRelativePathRedirect()
{
$this->client->setUri($this->baseuri . 'testRelativeRedirections.php');
$this->client->setParameterGet(['redirect' => 'relpath']);
$this->client->setOptions(['maxredirects' => 1]);
// Set the new expected URI
$uri = clone $this->client->getUri();
$uri->setPath(rtrim(dirname($uri->getPath()), '/') . '/path/to/fake/file.ext');
$uri = $uri->__toString();
$this->client->send();
$this->assertEquals(
sprintf('%s?redirect=relpath', $uri),
$this->client->getUri()->toString(),
sprintf('The new location is not as expected: %s', $this->client->getUri()->toString())
);
}
/**
* HTTP Authentication Tests
*/
/**
* Test we can properly use Basic HTTP authentication
*/
public function testHttpAuthBasic()
{
$this->client->setUri($this->baseuri . 'testHttpAuth.php');
$this->client->setParameterGet([
'user' => 'alice',
'pass' => 'secret',
'method' => 'Basic',
]);
// First - fail password
$this->client->setAuth('alice', 'wrong');
$res = $this->client->send();
$this->assertEquals(401, $res->getStatusCode(), 'Expected HTTP 401 response was not received');
// Now use good password
$this->client->setAuth('alice', 'secret');
$res = $this->client->send();
$this->assertEquals(200, $res->getStatusCode(), 'Expected HTTP 200 response was not received');
}
/**
* Test that we can properly use Basic HTTP authentication by specifying username and password
* in the URI
*/
public function testHttpAuthBasicWithCredentialsInUri()
{
$uri = str_replace('http://', 'http://%s:%s@', $this->baseuri) . 'testHttpAuth.php';
$this->client->setParameterGet([
'user' => 'alice',
'pass' => 'secret',
'method' => 'Basic',
]);
// First - fail password
$this->client->setUri(sprintf($uri, 'alice', 'wrong'));
$this->client->setMethod('GET');
$res = $this->client->send();
$this->assertEquals(401, $res->getStatusCode(), 'Expected HTTP 401 response was not received');
// Now use good password
$this->client->setUri(sprintf($uri, 'alice', 'secret'));
$this->client->setMethod('GET');
$res = $this->client->send();
$this->assertEquals(200, $res->getStatusCode(), 'Expected HTTP 200 response was not received');
}
/**
* Cookie and Cookies Tests
*/
/**
* Test we can set string cookies with no jar
*/
public function testCookiesStringNoJar()
{
$this->client->setUri($this->baseuri . 'testCookies.php');
$cookies = [
'name' => 'value',
'cookie' => 'crumble',
];
$this->client->setCookies($cookies);
$res = $this->client->send();
$this->assertEquals(
$res->getBody(),
serialize($cookies),
'Response body does not contain the expected cookies'
);
}
/**
* Make sure we can set an array of object cookies
*/
public function testSetCookieObjectArray()
{
$this->client->setUri($this->baseuri . 'testCookies.php');
$refuri = $this->client->getUri();
$cookies = [
'chocolate' => 'chips',
'crumble' => 'apple',
'another' => 'cookie',
];
$this->client->setCookies($cookies);
$res = $this->client->send();
$this->assertEquals(
$res->getBody(),
serialize($cookies),
'Response body does not contain the expected cookies'
);
}
/**
* Make sure we can set an array of string cookies
*/
public function testSetCookieStringArray()
{
$this->client->setUri($this->baseuri . 'testCookies.php');
$cookies = [
'chocolate' => 'chips',
'crumble' => 'apple',
'another' => 'cookie',
];
$this->client->setCookies($cookies);
$res = $this->client->send();
$this->assertEquals(
$res->getBody(),
serialize($cookies),
'Response body does not contain the expected cookies'
);
}
/**
* File Upload Tests
*/
/**
* Test we can upload raw data as a file
*/
public function testUploadRawData()
{
if (! ini_get('file_uploads')) {
$this->markTestSkipped('File uploads disabled.');
}
$this->client->setUri($this->baseuri . 'testUploads.php');
$rawdata = file_get_contents(__FILE__);
$this->client->setFileUpload('myfile.txt', 'uploadfile', $rawdata, 'text/plain');
$this->client->setMethod('POST');
$res = $this->client->send();
$body = sprintf('uploadfile myfile.txt text/plain %d' . "\n", strlen($rawdata));
$this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
}
/**
* Test we can upload an existing file
*/
public function testUploadLocalFile()
{
if (! ini_get('file_uploads')) {
$this->markTestSkipped('File uploads disabled.');
}
$this->client->setUri($this->baseuri . 'testUploads.php');
$this->client->setFileUpload(__FILE__, 'uploadfile', null, 'text/x-foo-bar');
$this->client->setMethod('POST');
$res = $this->client->send();
$size = filesize(__FILE__);
$body = sprintf('uploadfile %s text/x-foo-bar %d' . "\n", basename(__FILE__), $size);
$this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
}
public function testUploadLocalDetectMime()
{
if (! ini_get('file_uploads')) {
$this->markTestSkipped('File uploads disabled.');
}
$detect = null;
if (function_exists('finfo_file')) {
$f = @finfo_open(FILEINFO_MIME);
if ($f) {
$detect = 'finfo';
}
} elseif (function_exists('mime_content_type')) {
if (mime_content_type(__FILE__)) {
$detect = 'mime_magic';
}
}
if (! $detect) {
$this->markTestSkipped(
'No MIME type detection capability (fileinfo or mime_magic extensions) is available'
);
}
$file = __DIR__ . '/_files/staticFile.jpg';
$this->client->setUri($this->baseuri . 'testUploads.php');
$this->client->setFileUpload($file, 'uploadfile');
$this->client->setMethod('POST');
$res = $this->client->send();
$size = filesize($file);
$body = sprintf('uploadfile %s image/jpeg %d' . "\n", basename($file), $size);
$this->assertEquals(
$body,
$res->getBody(),
'Response body does not include expected upload parameters (detect: ' . $detect . ')'
);
}
public function testUploadNameWithSpecialChars()
{
if (! ini_get('file_uploads')) {
$this->markTestSkipped('File uploads disabled.');
}
$this->client->setUri($this->baseuri . 'testUploads.php');
$rawdata = file_get_contents(__FILE__);
$this->client->setFileUpload('/some strage/path%/with[!@#$&]/myfile.txt', 'uploadfile', $rawdata, 'text/plain');
$this->client->setMethod('POST');
$res = $this->client->send();
$body = 'uploadfile myfile.txt text/plain ' . strlen($rawdata) . "\n";
$this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
}
public function testStaticLargeFileDownload()
{
$this->client->setUri($this->baseuri . 'staticFile.jpg');
$got = $this->client->send()->getBody();
$expected = $this->getTestFileContents('staticFile.jpg');
$this->assertEquals($expected, $got, 'Downloaded file does not seem to match!');
}
/**
* Test that one can upload multiple files with the same form name, as an
* array
*
* @link http://framework.zend.com/issues/browse/ZF-5744
*/
public function testMultipleFilesWithSameFormNameZF5744()
{
if (! ini_get('file_uploads')) {
$this->markTestSkipped('File uploads disabled.');
}
$rawData = 'Some test raw data here...';
$this->client->setUri($this->baseuri . 'testUploads.php');
$files = ['file1.txt', 'file2.txt', 'someotherfile.foo'];
$expectedBody = '';
foreach ($files as $filename) {
$this->client->setFileUpload($filename, 'uploadfile[]', $rawData, 'text/plain');
$expectedBody .= sprintf('uploadfile %s text/plain %d' . "\n", $filename, strlen($rawData));
}
$this->client->setMethod('POST');
$res = $this->client->send();
$this->assertEquals(
$expectedBody,
$res->getBody(),
'Response body does not include expected upload parameters'
);
}
/**
* Test that lines that might be evaluated as boolean false do not break
* the reading prematurely.
*
* @group ZF-4238
*/
public function testZF4238FalseLinesInResponse()
{
$this->client->setUri($this->baseuri . 'ZF4238-zerolineresponse.txt');
$got = $this->client->send()->getBody();
$expected = $this->getTestFileContents('ZF4238-zerolineresponse.txt');
$this->assertEquals($expected, $got);
}
public function testStreamResponse()
{
if (! $this->client->getAdapter() instanceof Adapter\StreamInterface) {
$this->markTestSkipped('Current adapter does not support streaming');
return;
}
$this->client->setUri($this->baseuri . 'staticFile.jpg');
$this->client->setStream();
$response = $this->client->send();
$this->assertInstanceOf(Stream::class, $response, 'Request did not return stream response!');
$this->assertInternalType('resource', $response->getStream(), 'Request does not contain stream!');
$streamName = $response->getStreamName();
$streamRead = stream_get_contents($response->getStream());
$fileRead = file_get_contents($streamName);
$expected = $this->getTestFileContents('staticFile.jpg');
$this->assertEquals($expected, $streamRead, 'Downloaded stream does not seem to match!');
$this->assertEquals($expected, $fileRead, 'Downloaded file does not seem to match!');
}
public function testStreamResponseBody()
{
$this->markTestSkipped('To check with the new ZF2 implementation');
if (! $this->client->getAdapter() instanceof Adapter\StreamInterface) {
$this->markTestSkipped('Current adapter does not support streaming');
return;
}
$this->client->setUri($this->baseuri . 'staticFile.jpg');
$this->client->setStream();
$response = $this->client->send();
$this->assertInstanceOf(Stream::class, $response, 'Request did not return stream response!');
$this->assertInternalType('resource', $response->getStream(), 'Request does not contain stream!');
$body = $response->getBody();
$expected = $this->getTestFileContents('staticFile.jpg');
$this->assertEquals($expected, $body, 'Downloaded stream does not seem to match!');
}
public function testStreamResponseNamed()
{
if (! $this->client->getAdapter() instanceof Adapter\StreamInterface) {
$this->markTestSkipped('Current adapter does not support streaming');
return;
}
$this->client->setUri($this->baseuri . 'staticFile.jpg');
$outfile = tempnam(sys_get_temp_dir(), 'outstream');
$this->client->setStream($outfile);
$response = $this->client->send();
$this->assertInstanceOf(Stream::class, $response, 'Request did not return stream response!');
$this->assertInternalType('resource', $response->getStream(), 'Request does not contain stream!');
$this->assertEquals($outfile, $response->getStreamName());
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | true |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/CurlTest.php | test/Client/CurlTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client;
use Zend\Config\Config;
use Zend\Http\Client;
use Zend\Http\Client\Adapter;
use Zend\Http\Client\Adapter\Curl;
use Zend\Http\Client\Adapter\Exception\InvalidArgumentException;
use Zend\Http\Client\Adapter\Exception\RuntimeException;
use Zend\Http\Client\Adapter\Exception\TimeoutException;
use Zend\Stdlib\ErrorHandler;
/**
* This Testsuite includes all Zend_Http_Client that require a working web
* server to perform. It was designed to be extendable, so that several
* test suites could be run against several servers, with different client
* adapters and configurations.
*
* Note that $this->baseuri must point to a directory on a web server
* containing all the files under the files directory. You should symlink
* or copy these files and set 'baseuri' properly.
*
* You can also set the proper constand in your test configuration file to
* point to the right place.
*
* @group Zend_Http
* @group Zend_Http_Client
*/
class CurlTest extends CommonHttpTests
{
/**
* Configuration array
*
* @var array
*/
protected $config = [
'adapter' => Curl::class,
'curloptions' => [
CURLOPT_INFILESIZE => 102400000,
],
];
protected function setUp()
{
if (! extension_loaded('curl')) {
$this->markTestSkipped('cURL is not installed, marking all Http Client Curl Adapter tests skipped.');
}
parent::setUp();
}
/**
* Off-line common adapter tests
*/
/**
* Test that we can set a valid configuration array with some options
*/
public function testConfigSetAsArray()
{
$config = [
'timeout' => 500,
'someoption' => 'hasvalue',
];
$this->_adapter->setOptions($config);
$hasConfig = $this->_adapter->getConfig();
foreach ($config as $k => $v) {
$this->assertEquals($v, $hasConfig[$k]);
}
}
/**
* Test that a Zend_Config object can be used to set configuration
*
* @link http://framework.zend.com/issues/browse/ZF-5577
*/
public function testConfigSetAsZendConfig()
{
$config = new Config([
'timeout' => 400,
'nested' => [
'item' => 'value',
],
]);
$this->_adapter->setOptions($config);
$hasConfig = $this->_adapter->getConfig();
$this->assertEquals($config->timeout, $hasConfig['timeout']);
$this->assertEquals($config->nested->item, $hasConfig['nested']['item']);
}
public function provideValidTimeoutConfig()
{
return [
'integer' => [10],
'numeric' => ['10'],
];
}
/**
* @dataProvider provideValidTimeoutConfig
*/
public function testPassValidTimeout($timeout)
{
$adapter = new Adapter\Curl();
$adapter->setOptions(['timeout' => $timeout]);
$adapter->connect('framework.zend.com');
}
public function testThrowInvalidArgumentExceptionOnNonIntegerAndNonNumericStringTimeout()
{
$adapter = new Adapter\Curl();
$adapter->setOptions(['timeout' => 'timeout']);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('integer or numeric string expected, got string');
$adapter->connect('framework.zend.com');
}
/**
* Check that an exception is thrown when trying to set invalid config
*
* @dataProvider invalidConfigProvider
*
* @param mixed $config
*/
public function testSetConfigInvalidConfig($config)
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Array or Traversable object expected');
$this->_adapter->setOptions($config);
}
public function testSettingInvalidCurlOption()
{
$config = [
'adapter' => Curl::class,
'curloptions' => [-PHP_INT_MAX => true],
];
$this->client = new Client($this->client->getUri(true), $config);
// Ignore curl warning: Invalid curl configuration option
ErrorHandler::start();
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Unknown or erroreous cURL option');
try {
$this->client->send();
} finally {
ErrorHandler::stop();
}
}
public function testRedirectWithGetOnly()
{
$this->client->setUri($this->baseuri . 'testRedirections.php');
// Set some parameters
$this->client->setParameterGet(['swallow', 'african']);
// Request
$res = $this->client->send();
$this->assertEquals(3, $this->client->getRedirectionsCount(), 'Redirection counter is not as expected');
// Make sure the body does *not* contain the set parameters
$this->assertNotContains('swallow', $res->getBody());
$this->assertNotContains('Camelot', $res->getBody());
}
/**
* This is a specific problem of the request type: If you let cURL handle redirects internally
* but start with a POST request that sends data then the location ping-pong will lead to an
* Content-Length: x\r\n GET request of the client that the server won't answer because no content is sent.
*
* Set CURLOPT_FOLLOWLOCATION = false for this type of request and let the Zend_Http_Client handle redirects
* in his own loop.
*/
public function testRedirectPostToGetWithCurlFollowLocationOptionLeadsToTimeout()
{
$adapter = new Adapter\Curl();
$this->client->setAdapter($adapter);
$adapter->setOptions([
'curloptions' => [
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 1,
],
]);
$this->client->setUri($this->baseuri . 'testRedirections.php');
// Set some parameters
$this->client->setParameterGet(['swallow' => 'african']);
$this->client->setParameterPost(['Camelot' => 'A silly place']);
$this->client->setMethod('POST');
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Read timed out');
$this->client->send();
}
/**
* @group ZF-3758
* @link http://framework.zend.com/issues/browse/ZF-3758
*/
public function testPutFileContentWithHttpClient()
{
// Method 1: Using the binary string of a file to PUT
$this->client->setUri($this->baseuri . 'testRawPostData.php');
$putFileContents = file_get_contents(__DIR__ . '/_files/staticFile.jpg');
$this->client->setRawBody($putFileContents);
$this->client->setMethod('PUT');
$this->client->send();
$this->assertEquals($putFileContents, $this->client->getResponse()->getBody());
}
/**
* @group ZF-3758
* @link http://framework.zend.com/issues/browse/ZF-3758
*/
public function testPutFileHandleWithHttpClient()
{
$this->client->setUri($this->baseuri . 'testRawPostData.php');
$putFileContents = file_get_contents(__DIR__ . '/_files/staticFile.jpg');
// Method 2: Using a File-Handle to the file to PUT the data
$putFilePath = __DIR__ . '/_files/staticFile.jpg';
$putFileHandle = fopen($putFilePath, 'r');
$putFileSize = filesize($putFilePath);
$adapter = new Adapter\Curl();
$this->client->setAdapter($adapter);
$adapter->setOptions([
'curloptions' => [
CURLOPT_INFILE => $putFileHandle,
CURLOPT_INFILESIZE => $putFileSize,
],
]);
$this->client->setMethod('PUT');
$this->client->send();
$this->assertEquals(gzcompress($putFileContents), gzcompress($this->client->getResponse()->getBody()));
}
public function testWritingAndNotConnectedWithCurlHandleThrowsException()
{
$adapter = new Adapter\Curl();
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Trying to write but we are not connected');
$adapter->write('GET', 'someUri');
}
public function testSetConfigIsNotArray()
{
$adapter = new Adapter\Curl();
$this->expectException(InvalidArgumentException::class);
$adapter->setOptions('foo');
}
public function testSetCurlOptions()
{
$adapter = new Adapter\Curl();
$adapter->setCurlOption('foo', 'bar')
->setCurlOption('bar', 'baz');
$this->assertEquals(
['curloptions' => ['foo' => 'bar', 'bar' => 'baz']],
$this->readAttribute($adapter, 'config')
);
}
/**
* @group 4213
*/
public function testSetOptionsMergesCurlOptions()
{
$adapter = new Adapter\Curl();
$adapter->setOptions([
'curloptions' => [
'foo' => 'bar',
],
]);
$adapter->setOptions([
'curloptions' => [
'bar' => 'baz',
],
]);
$this->assertEquals(
['curloptions' => ['foo' => 'bar', 'bar' => 'baz']],
$this->readAttribute($adapter, 'config')
);
}
public function testWorkWithProxyConfiguration()
{
$adapter = new Adapter\Curl();
$adapter->setOptions([
'proxy_host' => 'localhost',
'proxy_port' => 80,
'proxy_user' => 'foo',
'proxy_pass' => 'baz',
]);
$expected = [
'curloptions' => [
CURLOPT_PROXYUSERPWD => 'foo:baz',
CURLOPT_PROXY => 'localhost',
CURLOPT_PROXYPORT => 80,
],
];
$this->assertEquals(
$expected,
$this->readAttribute($adapter, 'config')
);
}
public function testSslVerifyPeerCanSetOverOption()
{
$adapter = new Adapter\Curl();
$adapter->setOptions([
'sslverifypeer' => true,
]);
$expected = [
'curloptions' => [
CURLOPT_SSL_VERIFYPEER => true,
],
];
$this->assertEquals(
$expected,
$this->readAttribute($adapter, 'config')
);
}
/**
* @group ZF-7040
*/
public function testGetCurlHandle()
{
$adapter = new Adapter\Curl();
$adapter->setOptions(['timeout' => 2, 'maxredirects' => 1]);
$adapter->connect('framework.zend.com');
$this->assertInternalType('resource', $adapter->getHandle());
}
/**
* @group ZF-9857
*/
public function testHeadRequest()
{
$this->client->setUri($this->baseuri . 'testRawPostData.php');
$adapter = new Adapter\Curl();
$this->client->setAdapter($adapter);
$this->client->setMethod('HEAD');
$this->client->send();
$this->assertEquals('', $this->client->getResponse()->getBody());
}
public function testAuthorizeHeader()
{
// We just need someone to talk to
$this->client->setUri($this->baseuri . 'testHttpAuth.php');
$adapter = new Adapter\Curl();
$this->client->setAdapter($adapter);
$uid = 'alice';
$pwd = 'secret';
$hash = base64_encode($uid . ':' . $pwd);
$header = 'Authorization: Basic ' . $hash;
$this->client->setAuth($uid, $pwd);
$res = $this->client->send();
$curlInfo = curl_getinfo($adapter->getHandle());
$this->assertArrayHasKey(
'request_header',
$curlInfo,
'Expecting request_header in curl_getinfo() return value'
);
$this->assertContains($header, $curlInfo['request_header'], 'Expecting valid basic authorization header');
}
/**
* @group 4555
*/
public function testResponseDoesNotDoubleDecodeGzippedBody()
{
$this->client->setUri($this->baseuri . 'testCurlGzipData.php');
$adapter = new Adapter\Curl();
$adapter->setOptions([
'curloptions' => [
CURLOPT_ENCODING => '',
],
]);
$this->client->setAdapter($adapter);
$this->client->setMethod('GET');
$this->client->send();
$this->assertEquals('Success', $this->client->getResponse()->getBody());
}
public function testSetCurlOptPostFields()
{
$this->client->setUri($this->baseuri . 'testRawPostData.php');
$adapter = new Adapter\Curl();
$adapter->setOptions([
'curloptions' => [
CURLOPT_POSTFIELDS => 'foo=bar',
],
]);
$this->client->setAdapter($adapter);
$this->client->setMethod('POST');
$this->client->send();
$this->assertEquals('foo=bar', $this->client->getResponse()->getBody());
}
/**
* @group ZF-7683
* @see https://github.com/zendframework/zend-http/pull/53
*
* Note: The headers stored in ZF7683-chunked.php are case insensitive
*/
public function testNoCaseSensitiveHeaderName()
{
$this->client->setUri($this->baseuri . 'ZF7683-chunked.php');
$adapter = new Adapter\Curl();
$adapter->setOptions([
'curloptions' => [
CURLOPT_ENCODING => '',
],
]);
$this->client->setAdapter($adapter);
$this->client->setMethod('GET');
$this->client->send();
$headers = $this->client->getResponse()->getHeaders();
$this->assertFalse($headers->has('Transfer-Encoding'));
$this->assertFalse($headers->has('Content-Encoding'));
}
public function testSslCaPathAndFileConfig()
{
$adapter = new Adapter\Curl();
$options = [
'sslcapath' => __DIR__ . DIRECTORY_SEPARATOR . '/_files',
'sslcafile' => 'ca-bundle.crt',
];
$adapter->setOptions($options);
$config = $this->readAttribute($adapter, 'config');
$this->assertEquals($options['sslcapath'], $config['sslcapath']);
$this->assertEquals($options['sslcafile'], $config['sslcafile']);
}
public function testTimeout()
{
$this->client
->setUri($this->baseuri . 'testTimeout.php')
->setOptions([
'timeout' => 1,
]);
$adapter = new Adapter\Curl();
$this->client->setAdapter($adapter);
$this->client->setMethod('GET');
$timeoutException = null;
try {
$this->client->send();
} catch (TimeoutException $x) {
$timeoutException = $x;
}
$this->assertNotNull($timeoutException);
}
public function testTimeoutWithStream()
{
$this->client
->setOptions([
'timeout' => 1,
])
->setStream(true)
->setMethod('GET')
->setUri(
getenv('TESTS_ZEND_HTTP_CLIENT_BIGRESOURCE_URI') ?:
'http://de.releases.ubuntu.com/16.04.1/ubuntu-16.04.1-server-i386.iso'
);
$error = null;
try {
$this->client->send();
} catch (\Exception $x) {
$error = $x;
}
$this->assertNotNull($error, 'Failed to detect timeout in cURL adapter');
}
/**
* @see https://github.com/zendframework/zend-http/pull/184
*/
public function testMustRemoveProxyConnectionEstablishedLine()
{
$proxy = getenv('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY');
if (! $proxy) {
$this->markTestSkipped('Proxy is not configured');
}
list($proxyHost, $proxyPort) = explode(':', $proxy);
$this->client->setAdapter(new Adapter\Curl());
$this->client->setOptions([
'proxyhost' => $proxyHost,
'proxyport' => $proxyPort,
]);
$this->client->setUri('https://framework.zend.com');
$this->client->setMethod('GET');
$this->client->send();
$response = $this->client->getResponse();
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('HTTP/1.1 200 OK', trim(strstr($response, "\n", true)));
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/TestAsset/MockAdapter.php | test/Client/TestAsset/MockAdapter.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client\TestAsset;
use Zend\Http\Client\Adapter\Test;
class MockAdapter extends Test
{
public $config = [];
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/TestAsset/MockClient.php | test/Client/TestAsset/MockClient.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Client\TestAsset;
use Zend\Http\Client;
use Zend\Http\Client\Adapter\Socket;
use Zend\Http\Request;
class MockClient extends Client
{
public $config = [
'maxredirects' => 5,
'strictredirects' => false,
'useragent' => 'Zend_Http_Client',
'timeout' => 10,
'adapter' => Socket::class,
'httpversion' => Request::VERSION_11,
'keepalive' => false,
'storeresponse' => true,
'strict' => true,
'outputstream' => false,
'encodecookies' => true,
];
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testPostData.php | test/Client/_files/testPostData.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
echo serialize($_POST);
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testRawGetData.php | test/Client/_files/testRawGetData.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
echo serialize($_GET);
readfile('php://input');
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testStreamRequest.php | test/Client/_files/testStreamRequest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
readfile('php://input');
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testPatchData.php | test/Client/_files/testPatchData.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
readfile("php://input");
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testUploads.php | test/Client/_files/testUploads.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
if (! empty($_FILES)) {
foreach ($_FILES as $name => $file) {
if (is_array($file['name'])) {
foreach ($file['name'] as $k => $v) {
echo "$name $v {$file['type'][$k]} {$file['size'][$k]}\n";
}
} else {
echo "$name {$file['name']} {$file['type']} {$file['size']}\n";
}
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testExceptionOnReadTimeout.php | test/Client/_files/testExceptionOnReadTimeout.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
/**
* This script does nothing but sleep, and is used to test how
* Zend_Http_Client handles an exceeded timeout
*/
sleep(5);
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/ZF7683-chunked.php | test/Client/_files/ZF7683-chunked.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
// intentional use of case-insensitive header name
header('Transfer-encoding: chunked');
header('content-encoding: gzip');
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testOptionsData.php | test/Client/_files/testOptionsData.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
readfile("php://input");
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testResetParameters.php | test/Client/_files/testResetParameters.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
echo serialize($_GET) . "\n" . serialize($_POST);
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testMultibyteChunkedResponseZF6218.php | test/Client/_files/testMultibyteChunkedResponseZF6218.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
header("Content-type: text/plain; charset=UTF-8");
@ob_end_flush();
@ob_implicit_flush(true);
$text = <<<EOTEXT
לִבִּי בְמִזְרָח וְאָנֹכִי בְּסוֹף מַעֲרָב
אֵיךְ אֶטְעֲמָה אֵת אֲשֶׁר אֹכַל וְאֵיךְ יֶעֱרָב
אֵיכָה אֲשַׁלֵּם נְדָרַי וָאֱסָרַי, בְּעוֹד
צִיּוֹן בְּחֶבֶל אֱדוֹם וַאֲנִי בְּכֶבֶל עֲרָב
יֵקַל בְּעֵינַי עֲזֹב כָּל טוּב סְפָרַד, כְּמוֹ
יֵקַר בְּעֵינַי רְאוֹת עַפְרוֹת דְּבִיר נֶחֱרָב.
EOTEXT;
echo $text;
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testCookies.php | test/Client/_files/testCookies.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
echo serialize($_COOKIE);
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testRawPostData.php | test/Client/_files/testRawPostData.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
readfile('php://input');
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/ZF9404-doubleContentLength.php | test/Client/_files/ZF9404-doubleContentLength.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
$clength = filesize(__FILE__);
header(sprintf('Content-length: %s', $clength));
header(sprintf('Content-length: %s', $clength), false);
readfile(__FILE__);
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testConnectTimeout.php | test/Client/_files/testConnectTimeout.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
echo 'start';
sleep(3);
echo 'end';
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testRedirections.php | test/Client/_files/testRedirections.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
if (! isset($_GET['redirection'])) {
$_GET['redirection'] = 0;
/**
* Create session cookie, but only on first redirect
*/
setcookie('zf2testSessionCookie', 'positive');
/**
* Create a long living cookie
*/
setcookie('zf2testLongLivedCookie', 'positive', time() + 2678400);
/**
* Create a cookie that should be invalid on arrival
*/
setcookie('zf2testExpiredCookie', 'negative', time() - 2400);
}
$_GET['redirection']++;
$https = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
if (! isset($_GET['redirection']) || $_GET['redirection'] < 4) {
$target = 'http' . ($https ? 's://' : '://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . $target . '?redirection=' . $_GET['redirection']);
} else {
var_dump($_GET);
var_dump($_POST);
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/fwrite.php | test/Client/_files/fwrite.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Http\Client\Adapter;
/**
* This is a stub for PHP's `fwrite` function. It
* allows us to check that a write operation to a
* socket producing a returned "0 bytes" written
* is actually valid.
*/
function fwrite($socket, $request)
{
return 0;
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testSimpleRequests.php | test/Client/_files/testSimpleRequests.php | Success
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testDeleteData.php | test/Client/_files/testDeleteData.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
readfile("php://input");
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testHeaders.php | test/Client/_files/testHeaders.php | php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false | |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testTimeout.php | test/Client/_files/testTimeout.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
sleep(2);
echo 'done.';
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testGetData.php | test/Client/_files/testGetData.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
echo serialize($_GET);
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testRelativeRedirections.php | test/Client/_files/testRelativeRedirections.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
if (! isset($_GET['redirect'])) {
$_GET['redirect'] = null;
}
switch ($_GET['redirect']) {
case 'abpath':
header("Location: /path/to/fake/file.ext?redirect=abpath");
break;
case 'relpath':
header("Location: path/to/fake/file.ext?redirect=relpath");
break;
default:
echo "Redirections done.";
break;
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testCurlGzipData.php | test/Client/_files/testCurlGzipData.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
header('Content-Encoding: gzip');
echo gzcompress('Success');
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Client/_files/testHttpAuth.php | test/Client/_files/testHttpAuth.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
$pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;
$guser = isset($_GET['user']) ? $_GET['user'] : null;
$gpass = isset($_GET['pass']) ? $_GET['pass'] : null;
$method = isset($_GET['method']) ? $_GET['method'] : 'Basic';
if (! $user || ! $pass || $user != $guser || $pass != $gpass) {
header('WWW-Authenticate: ' . $method . ' realm="ZendTest"');
header('HTTP/1.0 401 Unauthorized');
}
echo serialize($_GET), "\n", $user, "\n", $pass, "\n";
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Response/ResponseStreamTest.php | test/Response/ResponseStreamTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Response;
use PHPUnit\Framework\TestCase;
use Zend\Http\Response\Stream;
class ResponseStreamTest extends TestCase
{
public function testResponseFactoryFromStringCreatesValidResponse()
{
$string = 'HTTP/1.0 200 OK' . "\r\n\r\n" . 'Foo Bar' . "\r\n";
$stream = fopen('php://temp', 'rb+');
fwrite($stream, 'Bar Foo');
rewind($stream);
$response = Stream::fromStream($string, $stream);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals("Foo Bar\r\nBar Foo", $response->getBody());
}
/**
* @group 6027
*
* @covers \Zend\Http\Response\Stream::fromStream
*/
public function testResponseFactoryFromEmptyStringCreatesValidResponse()
{
$stream = fopen('php://temp', 'rb+');
fwrite($stream, 'HTTP/1.0 200 OK' . "\r\n\r\n" . 'Foo Bar' . "\r\n" . 'Bar Foo');
rewind($stream);
$response = Stream::fromStream('', $stream);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals("Foo Bar\r\nBar Foo", $response->getBody());
}
public function testGzipResponse()
{
$stream = fopen(__DIR__ . '/../_files/response_gzip', 'rb');
$headers = '';
while (false !== ($newLine = fgets($stream))) {
$headers .= $newLine;
if ($headers == "\n" || $headers == "\r\n") {
break;
}
}
$headers .= fread($stream, 100); // Should accept also part of body as text
$res = Stream::fromStream($headers, $stream);
$this->assertEquals('gzip', $res->getHeaders()->get('Content-encoding')->getFieldValue());
$this->assertEquals('0b13cb193de9450aa70a6403e2c9902f', md5($res->getBody()));
$this->assertEquals('f24dd075ba2ebfb3bf21270e3fdc5303', md5($res->getContent()));
}
public function test300isRedirect()
{
$values = $this->readResponse('response_302');
$response = Stream::fromStream($values['data'], $values['stream']);
$this->assertEquals(302, $response->getStatusCode(), 'Response code is expected to be 302, but it\'s not.');
$this->assertFalse($response->isClientError(), 'Response is an error, but isClientError() returned true');
$this->assertFalse($response->isForbidden(), 'Response is an error, but isForbidden() returned true');
$this->assertFalse($response->isInformational(), 'Response is an error, but isInformational() returned true');
$this->assertFalse($response->isNotFound(), 'Response is an error, but isNotFound() returned true');
$this->assertFalse($response->isOk(), 'Response is an error, but isOk() returned true');
$this->assertFalse($response->isServerError(), 'Response is an error, but isServerError() returned true');
$this->assertTrue($response->isRedirect(), 'Response is an error, but isRedirect() returned false');
$this->assertFalse($response->isSuccess(), 'Response is an error, but isSuccess() returned true');
}
/**
* Helper function: read test response from file
*
* @param string $response
* @return string
*/
protected function readResponse($response)
{
$stream = fopen(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR
. $response, 'rb');
$data = '';
while (false !== ($newLine = fgets($stream))) {
$data .= $newLine;
if ($newLine == "\n" || $newLine == "\r\n") {
break;
}
}
$data .= fread($stream, 100); // Should accept also part of body as text
$return = [];
$return['stream'] = $stream;
$return['data'] = $data;
return $return;
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/PhpEnvironment/RemoteAddressTest.php | test/PhpEnvironment/RemoteAddressTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\PhpEnvironment;
use PHPUnit\Framework\TestCase;
use Zend\Http\PhpEnvironment\RemoteAddress as RemoteAddr;
class RemoteAddressTest extends TestCase
{
/**
* Original environemnt
*
* @var array
*/
protected $originalEnvironment;
/**
* @var RemoteAddr
*/
protected $remoteAddress;
/**
* Save the original environment and set up a clean one.
*/
public function setUp()
{
$this->originalEnvironment = [
'post' => $_POST,
'get' => $_GET,
'cookie' => $_COOKIE,
'server' => $_SERVER,
'env' => $_ENV,
'files' => $_FILES,
];
$_POST = [];
$_GET = [];
$_COOKIE = [];
$_SERVER = [];
$_ENV = [];
$_FILES = [];
$this->remoteAddress = new RemoteAddr();
}
/**
* Restore the original environment
*/
public function tearDown()
{
$_POST = $this->originalEnvironment['post'];
$_GET = $this->originalEnvironment['get'];
$_COOKIE = $this->originalEnvironment['cookie'];
$_SERVER = $this->originalEnvironment['server'];
$_ENV = $this->originalEnvironment['env'];
$_FILES = $this->originalEnvironment['files'];
}
public function testSetGetUseProxy()
{
$this->remoteAddress->setUseProxy(false);
$this->assertFalse($this->remoteAddress->getUseProxy());
}
public function testSetGetDefaultUseProxy()
{
$this->remoteAddress->setUseProxy();
$this->assertTrue($this->remoteAddress->getUseProxy());
}
public function testSetTrustedProxies()
{
$result = $this->remoteAddress->setTrustedProxies([
'192.168.0.10',
'192.168.0.1',
]);
$this->assertInstanceOf(RemoteAddr::class, $result);
}
public function testGetIpAddress()
{
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$this->assertEquals('127.0.0.1', $this->remoteAddress->getIpAddress());
}
public function testGetIpAddressFromProxy()
{
$this->remoteAddress->setUseProxy(true);
$this->remoteAddress->setTrustedProxies([
'192.168.0.10',
'10.0.0.1',
]);
$_SERVER['REMOTE_ADDR'] = '192.168.0.10';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '8.8.8.8, 10.0.0.1';
$this->assertEquals('8.8.8.8', $this->remoteAddress->getIpAddress());
}
public function testGetIpAddressFromProxyRemoteAddressNotTrusted()
{
$this->remoteAddress->setUseProxy(true);
$this->remoteAddress->setTrustedProxies([
'10.0.0.1',
]);
// the REMOTE_ADDR is not in the trusted IPs, possible attack here
$_SERVER['REMOTE_ADDR'] = '1.1.1.1';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '8.8.8.8, 10.0.0.1';
$this->assertEquals('1.1.1.1', $this->remoteAddress->getIpAddress());
}
/**
* Test to prevent attack on the HTTP_X_FORWARDED_FOR header
* The client IP is always the first on the left
*
* @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2
*/
public function testGetIpAddressFromProxyFakeData()
{
$this->remoteAddress->setUseProxy(true);
$this->remoteAddress->setTrustedProxies([
'192.168.0.10',
'10.0.0.1',
'10.0.0.2',
]);
$_SERVER['REMOTE_ADDR'] = '192.168.0.10';
// 1.1.1.1 is the first IP address from the right not representing a known proxy server; as such, we
// must treat it as a client IP.
$_SERVER['HTTP_X_FORWARDED_FOR'] = '8.8.8.8, 10.0.0.2, 1.1.1.1, 10.0.0.1';
$this->assertEquals('1.1.1.1', $this->remoteAddress->getIpAddress());
}
/**
* Tests if an empty string is returned if the server variable
* REMOTE_ADDR is not set.
*
* This happens when you run a local unit test, or a PHP script with
* PHP from the command line.
*/
public function testGetIpAddressReturnsEmptyStringOnNoRemoteAddr()
{
// Store the set IP address for later use
if (isset($_SERVER['REMOTE_ADDR'])) {
$ipAddress = $_SERVER['REMOTE_ADDR'];
unset($_SERVER['REMOTE_ADDR']);
}
$this->remoteAddress->setUseProxy(true);
$this->assertEquals('', $this->remoteAddress->getIpAddress());
if (isset($ipAddress)) {
$_SERVER['REMOTE_ADDR'] = $ipAddress;
}
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/PhpEnvironment/ResponseTest.php | test/PhpEnvironment/ResponseTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\PhpEnvironment;
use PHPUnit\Framework\TestCase;
use Zend\Http\Exception\InvalidArgumentException;
use Zend\Http\PhpEnvironment\Response;
class ResponseTest extends TestCase
{
/**
* Original environemnt
*
* @var array
*/
protected $originalEnvironment;
/**
* Save the original environment and set up a clean one.
*/
public function setUp()
{
$this->originalEnvironment = [
'post' => $_POST,
'get' => $_GET,
'cookie' => $_COOKIE,
'server' => $_SERVER,
'env' => $_ENV,
'files' => $_FILES,
];
$_POST = [];
$_GET = [];
$_COOKIE = [];
$_SERVER = [];
$_ENV = [];
$_FILES = [];
}
/**
* Restore the original environment
*/
public function tearDown()
{
$_POST = $this->originalEnvironment['post'];
$_GET = $this->originalEnvironment['get'];
$_COOKIE = $this->originalEnvironment['cookie'];
$_SERVER = $this->originalEnvironment['server'];
$_ENV = $this->originalEnvironment['env'];
$_FILES = $this->originalEnvironment['files'];
}
public function testReturnsOneOhVersionWhenDetectedInServerSuperglobal()
{
// HTTP/1.0
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
$response = new Response();
$this->assertSame(Response::VERSION_10, $response->getVersion());
}
public function testReturnsOneOneVersionWhenDetectedInServerSuperglobal()
{
// HTTP/1.1
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
$response = new Response();
$this->assertSame(Response::VERSION_11, $response->getVersion());
}
public function testFallsBackToVersionOneOhWhenServerSuperglobalVersionIsNotRecognized()
{
// unknown protocol or version -> fallback to HTTP/1.0
$_SERVER['SERVER_PROTOCOL'] = 'zf/2.0';
$response = new Response();
$this->assertSame(Response::VERSION_10, $response->getVersion());
}
public function testFallsBackToVersionOneOhWhenNoVersionDetectedInServerSuperglobal()
{
// undefined -> fallback to HTTP/1.0
unset($_SERVER['SERVER_PROTOCOL']);
$response = new Response();
$this->assertSame(Response::VERSION_10, $response->getVersion());
}
public function testCanExplicitlySetVersion()
{
$response = new Response();
$response->setVersion(Response::VERSION_11);
$this->assertSame(Response::VERSION_11, $response->getVersion());
$response->setVersion(Response::VERSION_10);
$this->assertSame(Response::VERSION_10, $response->getVersion());
$this->expectException(InvalidArgumentException::class);
$response->setVersion('zf/2.0');
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/PhpEnvironment/RequestTest.php | test/PhpEnvironment/RequestTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\PhpEnvironment;
use PHPUnit\Framework\TestCase;
use Zend\Http\Exception\InvalidArgumentException;
use Zend\Http\Header\GenericHeader;
use Zend\Http\Headers;
use Zend\Http\PhpEnvironment\Request;
use Zend\Stdlib\Parameters;
class RequestTest extends TestCase
{
/**
* Original environemnt
*
* @var array
*/
protected $originalEnvironment;
/**
* Save the original environment and set up a clean one.
*/
public function setUp()
{
$this->originalEnvironment = [
'post' => $_POST,
'get' => $_GET,
'cookie' => $_COOKIE,
'server' => $_SERVER,
'env' => $_ENV,
'files' => $_FILES,
];
$_POST = [];
$_GET = [];
$_COOKIE = [];
$_SERVER = [];
$_ENV = [];
$_FILES = [];
}
/**
* Restore the original environment
*/
public function tearDown()
{
$_POST = $this->originalEnvironment['post'];
$_GET = $this->originalEnvironment['get'];
$_COOKIE = $this->originalEnvironment['cookie'];
$_SERVER = $this->originalEnvironment['server'];
$_ENV = $this->originalEnvironment['env'];
$_FILES = $this->originalEnvironment['files'];
}
/**
* Data provider for testing base URL and path detection.
*/
public static function baseUrlAndPathProvider()
{
return [
[
[
'REQUEST_URI' => '/index.php/news/3?var1=val1&var2=val2',
'QUERY_URI' => 'var1=val1&var2=val2',
'SCRIPT_NAME' => '/index.php',
'PHP_SELF' => '/index.php/news/3',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/index.php',
'',
],
[
[
'REQUEST_URI' => '/public/index.php/news/3?var1=val1&var2=val2',
'QUERY_URI' => 'var1=val1&var2=val2',
'SCRIPT_NAME' => '/public/index.php',
'PHP_SELF' => '/public/index.php/news/3',
'SCRIPT_FILENAME' => '/var/web/html/public/index.php',
],
'/public/index.php',
'/public',
],
[
[
'REQUEST_URI' => '/index.php/news/3?var1=val1&var2=val2',
'SCRIPT_NAME' => '/home.php',
'PHP_SELF' => '/index.php/news/3',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/index.php',
'',
],
[
[
'REQUEST_URI' => '/index.php/news/3?var1=val1&var2=val2',
'SCRIPT_NAME' => '/home.php',
'PHP_SELF' => '/home.php',
'ORIG_SCRIPT_NAME' => '/index.php',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/index.php',
'',
],
[
[
'REQUEST_URI' => '/index.php/news/3?var1=val1&var2=val2',
'PHP_SELF' => '/index.php/news/3',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/index.php',
'',
],
[
[
'ORIG_PATH_INFO' => '/index.php/news/3',
'QUERY_STRING' => 'var1=val1&var2=val2',
'PHP_SELF' => '/index.php/news/3',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/index.php',
'',
],
[
[
'REQUEST_URI' => '/article/archive?foo=index.php',
'QUERY_STRING' => 'foo=index.php',
'SCRIPT_FILENAME' => '/var/www/zftests/index.php',
],
'',
'',
],
[
[
'REQUEST_URI' => '/html/index.php/news/3?var1=val1&var2=val2',
'PHP_SELF' => '/html/index.php/news/3',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/html/index.php',
'/html',
],
[
[
'REQUEST_URI' => '/dir/action',
'PHP_SELF' => '/dir/index.php',
'SCRIPT_FILENAME' => '/var/web/dir/index.php',
],
'/dir',
'/dir',
],
[
[
'SCRIPT_NAME' => '/~username/public/index.php',
'REQUEST_URI' => '/~username/public/',
'PHP_SELF' => '/~username/public/index.php',
'SCRIPT_FILENAME' => '/Users/username/Sites/public/index.php',
'ORIG_SCRIPT_NAME' => null,
],
'/~username/public',
'/~username/public',
],
// ZF2-206
[
[
'SCRIPT_NAME' => '/zf2tut/index.php',
'REQUEST_URI' => '/zf2tut/',
'PHP_SELF' => '/zf2tut/index.php',
'SCRIPT_FILENAME' => 'c:/ZF2Tutorial/public/index.php',
'ORIG_SCRIPT_NAME' => null,
],
'/zf2tut',
'/zf2tut',
],
[
[
'REQUEST_URI' => '/html/index.php/news/3?var1=val1&var2=/index.php',
'PHP_SELF' => '/html/index.php/news/3',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/html/index.php',
'/html',
],
[
[
'REQUEST_URI' => '/html/index.php/news/index.php',
'PHP_SELF' => '/html/index.php/news/index.php',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/html/index.php',
'/html',
],
// Test when url quert contains a full http url
[
[
'REQUEST_URI' => '/html/index.php?url=http://test.example.com/path/&foo=bar',
'PHP_SELF' => '/html/index.php',
'SCRIPT_FILENAME' => '/var/web/html/index.php',
],
'/html/index.php',
'/html',
],
];
}
/**
* @dataProvider baseUrlAndPathProvider
*
* @param array $server
* @param string $baseUrl
* @param string $basePath
*/
public function testBasePathDetection(array $server, $baseUrl, $basePath)
{
$_SERVER = $server;
$request = new Request();
$this->assertEquals($baseUrl, $request->getBaseUrl());
$this->assertEquals($basePath, $request->getBasePath());
}
/**
* Data provider for testing server provided headers.
*/
public static function serverHeaderProvider()
{
return [
[
[
'HTTP_USER_AGENT' => 'Dummy',
],
'User-Agent',
'Dummy',
],
[
[
'HTTP_CUSTOM_COUNT' => '0',
],
'Custom-Count',
'0',
],
[
[
'CONTENT_TYPE' => 'text/html',
],
'Content-Type',
'text/html',
],
[
[
'CONTENT_LENGTH' => 0,
],
'Content-Length',
0,
],
[
[
'CONTENT_LENGTH' => 0,
],
'Content-Length',
0,
],
[
[
'CONTENT_LENGTH' => 12,
],
'Content-Length',
12,
],
[
[
'CONTENT_MD5' => md5('a'),
],
'Content-MD5',
md5('a'),
],
];
}
/**
* @dataProvider serverHeaderProvider
*
* @param array $server
* @param string $name
* @param string $value
*/
public function testHeadersWithMinus(array $server, $name, $value)
{
$_SERVER = $server;
$request = new Request();
$header = $request->getHeaders()->get($name);
$this->assertNotEquals($header, false);
$this->assertEquals($name, $header->getFieldName($value));
$this->assertEquals($value, $header->getFieldValue($value));
}
/**
* @dataProvider serverHeaderProvider
*
* @param array $server
* @param string $name
*/
public function testRequestStringHasCorrectHeaderName(array $server, $name)
{
$_SERVER = $server;
$request = new Request();
$this->assertContains($name, $request->toString());
}
/**
* Data provider for testing server hostname.
*/
public static function serverHostnameProvider()
{
return [
[
[
'SERVER_NAME' => 'test.example.com',
'REQUEST_URI' => 'http://test.example.com/news',
],
'test.example.com',
'80',
'/news',
],
[
[
'HTTP_HOST' => 'test.example.com',
'REQUEST_URI' => 'http://test.example.com/news',
],
'test.example.com',
'80',
'/news',
],
[
[
'SERVER_NAME' => 'test.example.com',
'HTTP_HOST' => 'requested.example.com',
'REQUEST_URI' => 'http://test.example.com/news',
],
'requested.example.com',
'80',
'/news',
],
[
[
'SERVER_NAME' => 'test.example.com',
'HTTP_HOST' => '<script>alert("Spoofed host");</script>',
'REQUEST_URI' => 'http://test.example.com/news',
],
'test.example.com',
'80',
'/news',
],
[
[
'SERVER_NAME' => '[1:2:3:4:5:6::6]',
'SERVER_ADDR' => '1:2:3:4:5:6::6',
'SERVER_PORT' => '80',
'REQUEST_URI' => 'http://[1:2:3:4:5:6::6]/news',
],
'[1:2:3:4:5:6::6]',
'80',
'/news',
],
// Test for broken $_SERVER implementation from Windows-Safari
[
[
'SERVER_NAME' => '[1:2:3:4:5:6:]',
'SERVER_ADDR' => '1:2:3:4:5:6::6',
'SERVER_PORT' => '6',
'REQUEST_URI' => 'http://[1:2:3:4:5:6::6]/news',
],
'[1:2:3:4:5:6::6]',
'80',
'/news',
],
[
[
'SERVER_NAME' => 'test.example.com',
'SERVER_PORT' => '8080',
'REQUEST_URI' => 'http://test.example.com/news',
],
'test.example.com',
'8080',
'/news',
],
[
[
'SERVER_NAME' => 'test.example.com',
'SERVER_PORT' => '443',
'HTTPS' => 'on',
'REQUEST_URI' => 'https://test.example.com/news',
],
'test.example.com',
'443',
'/news',
],
// Test for HTTPS requests which are forwarded over a reverse proxy/load balancer
[
[
'SERVER_NAME' => 'test.example.com',
'SERVER_PORT' => '443',
'HTTP_X_FORWARDED_PROTO' => 'https',
'REQUEST_URI' => 'https://test.example.com/news',
],
'test.example.com',
'443',
'/news',
],
// Test when url query contains a full http url
[
[
'SERVER_NAME' => 'test.example.com',
'REQUEST_URI' => '/html/index.php?url=http://test.example.com/path/&foo=bar',
],
'test.example.com',
'80',
'/html/index.php?url=http://test.example.com/path/&foo=bar',
],
];
}
/**
* @dataProvider serverHostnameProvider
*
* @param array $server
* @param string $expectedHost
* @param string $expectedPort
* @param string $expectedRequestUri
*/
public function testServerHostnameProvider(array $server, $expectedHost, $expectedPort, $expectedRequestUri)
{
$_SERVER = $server;
$request = new Request();
$host = $request->getUri()->getHost();
$this->assertEquals($expectedHost, $host);
$uriParts = parse_url($_SERVER['REQUEST_URI']);
if (isset($uriParts['scheme'])) {
$scheme = $request->getUri()->getScheme();
$this->assertEquals($uriParts['scheme'], $scheme);
}
$port = $request->getUri()->getPort();
$this->assertEquals($expectedPort, $port);
$requestUri = $request->getRequestUri();
$this->assertEquals($expectedRequestUri, $requestUri);
}
/**
* Data provider for testing mapping $_FILES
*
* @return array
*/
public static function filesProvider()
{
return [
// single file
[
[
'file' => [
'name' => 'test1.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
],
[
'file' => [
'name' => 'test1.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
],
],
// file name with brackets and int keys
// file[], file[]
[
[
'file' => [
'name' => [
0 => 'test1.txt',
1 => 'test2.txt',
],
'type' => [
0 => 'text/plain',
1 => 'text/plain',
],
'tmp_name' => [
0 => '/tmp/phpXXX',
1 => '/tmp/phpXXX',
],
'error' => [
0 => 0,
1 => 0,
],
'size' => [
0 => 1,
1 => 1,
],
],
],
[
'file' => [
0 => [
'name' => 'test1.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
1 => [
'name' => 'test2.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
],
],
],
// file name with brackets and string keys
// file[one], file[two]
[
[
'file' => [
'name' => [
'one' => 'test1.txt',
'two' => 'test2.txt',
],
'type' => [
'one' => 'text/plain',
'two' => 'text/plain',
],
'tmp_name' => [
'one' => '/tmp/phpXXX',
'two' => '/tmp/phpXXX',
],
'error' => [
'one' => 0,
'two' => 0,
],
'size' => [
'one' => 1,
'two' => 1,
],
],
],
[
'file' => [
'one' => [
'name' => 'test1.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
'two' => [
'name' => 'test2.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
],
],
],
// multilevel file name
// file[], file[][], file[][][]
[
[
'file' => [
'name' => [
0 => 'test_0.txt',
1 => [
0 => 'test_10.txt',
],
2 => [
0 => [
0 => 'test_200.txt',
],
],
],
'type' => [
0 => 'text/plain',
1 => [
0 => 'text/plain',
],
2 => [
0 => [
0 => 'text/plain',
],
],
],
'tmp_name' => [
0 => '/tmp/phpXXX',
1 => [
0 => '/tmp/phpXXX',
],
2 => [
0 => [
0 => '/tmp/phpXXX',
],
],
],
'error' => [
0 => 0,
1 => [
0 => 0,
],
2 => [
0 => [
0 => 0,
],
],
],
'size' => [
0 => 1,
1 => [
0 => 1,
],
2 => [
0 => [
0 => 1,
],
],
],
],
],
[
'file' => [
0 => [
'name' => 'test_0.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
1 => [
0 => [
'name' => 'test_10.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
],
2 => [
0 => [
0 => [
'name' => 'test_200.txt',
'type' => 'text/plain',
'tmp_name' => '/tmp/phpXXX',
'error' => 0,
'size' => 1,
],
],
],
],
],
],
];
}
/**
* @dataProvider filesProvider
*
* @param array $files
* @param array $expectedFiles
*/
public function testRequestMapsPhpFies(array $files, array $expectedFiles)
{
$_FILES = $files;
$request = new Request();
$this->assertEquals($expectedFiles, $request->getFiles()->toArray());
}
public function testParameterRetrievalDefaultValue()
{
$request = new Request();
$p = new Parameters([
'foo' => 'bar',
]);
$request->setQuery($p);
$request->setPost($p);
$request->setFiles($p);
$request->setServer($p);
$request->setEnv($p);
$default = 15;
$this->assertSame($default, $request->getQuery('baz', $default));
$this->assertSame($default, $request->getPost('baz', $default));
$this->assertSame($default, $request->getFiles('baz', $default));
$this->assertSame($default, $request->getServer('baz', $default));
$this->assertSame($default, $request->getEnv('baz', $default));
$this->assertSame($default, $request->getHeaders('baz', $default));
$this->assertSame($default, $request->getHeader('baz', $default));
}
public function testRetrievingASingleValueForParameters()
{
$request = new Request();
$p = new Parameters([
'foo' => 'bar',
]);
$request->setQuery($p);
$request->setPost($p);
$request->setFiles($p);
$request->setServer($p);
$request->setEnv($p);
$this->assertSame('bar', $request->getQuery('foo'));
$this->assertSame('bar', $request->getPost('foo'));
$this->assertSame('bar', $request->getFiles('foo'));
$this->assertSame('bar', $request->getServer('foo'));
$this->assertSame('bar', $request->getEnv('foo'));
$headers = new Headers();
$h = new GenericHeader('foo', 'bar');
$headers->addHeader($h);
$request->setHeaders($headers);
$this->assertSame($headers, $request->getHeaders());
$this->assertSame($h, $request->getHeaders()->get('foo'));
$this->assertSame($h, $request->getHeader('foo'));
}
/**
* @group ZF2-480
*/
public function testBaseurlFallsBackToRootPathIfScriptFilenameIsNotSet()
{
$request = new Request();
$server = $request->getServer();
$server->set('SCRIPT_NAME', null);
$server->set('PHP_SELF', null);
$server->set('ORIG_SCRIPT_NAME', null);
$server->set('ORIG_SCRIPT_NAME', null);
$server->set('SCRIPT_FILENAME', null);
$this->assertEquals('', $request->getBaseUrl());
}
public function testAllowCustomMethodsFlagCanBeSetWithConstructor()
{
$_SERVER['REQUEST_METHOD'] = 'xcustomx';
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid HTTP method passed');
new Request(false);
}
/**
* @group 6896
*/
public function testHandlesUppercaseHttpsFlags()
{
$_SERVER['HTTPS'] = 'OFF';
$request = new Request();
$this->assertSame('http', $request->getUri()->getScheme());
}
/**
* @group 14
*/
public function testDetectBaseUrlDoesNotRaiseErrorOnEmptyBaseUrl()
{
// This is testing that a PHP error is not raised. It would normally be
// raised when we call `getBaseUrl()`; the assertion is essentially
// just to make sure we get past that point.
$_SERVER['SCRIPT_FILENAME'] = '';
$_SERVER['SCRIPT_NAME'] = '';
$request = new Request();
$url = $request->getBaseUrl();
// If no baseUrl is detected at all, an empty string is returned.
$this->assertEquals('', $url);
}
public function testDetectCorrectBaseUrlForConsoleRequests()
{
$_SERVER['argv'] = ['/home/user/package/vendor/bin/phpunit'];
$_SERVER['argc'] = 1;
$_SERVER['SCRIPT_FILENAME'] = '/home/user/package/vendor/bin/phpunit';
$_SERVER['SCRIPT_NAME'] = '/home/user/package/vendor/bin/phpunit';
$_SERVER['PHP_SELF'] = '/home/user/package/vendor/bin/phpunit';
$request = new Request();
$request->setRequestUri('/path/query/phpunit');
$this->assertSame('', $request->getBaseUrl());
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/LastModifiedTest.php | test/Header/LastModifiedTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\LastModified;
class LastModifiedTest extends TestCase
{
public function testExpiresFromStringCreatesValidLastModifiedHeader()
{
$lastModifiedHeader = LastModified::fromString('Last-Modified: Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertInstanceOf(HeaderInterface::class, $lastModifiedHeader);
$this->assertInstanceOf(LastModified::class, $lastModifiedHeader);
}
public function testLastModifiedGetFieldNameReturnsHeaderName()
{
$lastModifiedHeader = new LastModified();
$this->assertEquals('Last-Modified', $lastModifiedHeader->getFieldName());
}
public function testLastModifiedGetFieldValueReturnsProperValue()
{
$lastModifiedHeader = new LastModified();
$lastModifiedHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $lastModifiedHeader->getFieldValue());
}
public function testLastModifiedToStringReturnsHeaderFormattedString()
{
$lastModifiedHeader = new LastModified();
$lastModifiedHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Last-Modified: Sun, 06 Nov 1994 08:49:37 GMT', $lastModifiedHeader->toString());
}
/**
* Implementation specific tests are covered by DateTest
* @see ZendTest\Http\Header\DateTest
*/
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
LastModified::fromString("Last-Modified: Sun, 06 Nov 1994 08:49:37 GMT\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ExpectTest.php | test/Header/ExpectTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\Expect;
use Zend\Http\Header\HeaderInterface;
class ExpectTest extends TestCase
{
public function testExpectFromStringCreatesValidExpectHeader()
{
$expectHeader = Expect::fromString('Expect: xxx');
$this->assertInstanceOf(HeaderInterface::class, $expectHeader);
$this->assertInstanceOf(Expect::class, $expectHeader);
}
public function testExpectGetFieldNameReturnsHeaderName()
{
$expectHeader = new Expect();
$this->assertEquals('Expect', $expectHeader->getFieldName());
}
public function testExpectGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('Expect needs to be completed');
$expectHeader = new Expect();
$this->assertEquals('xxx', $expectHeader->getFieldValue());
}
public function testExpectToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('Expect needs to be completed');
$expectHeader = new Expect();
// @todo set some values, then test output
$this->assertEmpty('Expect: xxx', $expectHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Expect::fromString("Expect: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new Expect("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/LocationTest.php | test/Header/LocationTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\Location;
use Zend\Uri\File;
use Zend\Uri\Http;
use Zend\Uri\Mailto;
use Zend\Uri\Uri;
use Zend\Uri\UriFactory;
class LocationTest extends TestCase
{
/**
* @dataProvider locationFromStringCreatesValidLocationHeaderProvider
*
* @param string $uri The URL to redirect to
*/
public function testLocationFromStringCreatesValidLocationHeader($uri)
{
$locationHeader = Location::fromString('Location: ' . $uri);
$this->assertInstanceOf(HeaderInterface::class, $locationHeader);
$this->assertInstanceOf(Location::class, $locationHeader);
}
public function locationFromStringCreatesValidLocationHeaderProvider()
{
return [
['http://www.example.com'],
['https://www.example.com'],
['mailto://www.example.com'],
['file://www.example.com'],
];
}
/**
* Test that we can set a redirect to different URI-Schemes
*
* @dataProvider locationCanSetDifferentSchemeUrisProvider
*
* @param string $uri
* @param string $expectedClass
*/
public function testLocationCanSetDifferentSchemeUris($uri, $expectedClass)
{
$locationHeader = new Location();
$locationHeader->setUri($uri);
$this->assertAttributeInstanceOf($expectedClass, 'uri', $locationHeader);
}
/**
* Test that we can set a redirect to different URI-schemes via a class
*
* @dataProvider locationCanSetDifferentSchemeUrisProvider
*
* @param string $uri
* @param string $expectedClass
*/
public function testLocationCanSetDifferentSchemeUriObjects($uri, $expectedClass)
{
$uri = UriFactory::factory($uri);
$locationHeader = new Location();
$locationHeader->setUri($uri);
$this->assertAttributeInstanceOf($expectedClass, 'uri', $locationHeader);
}
/**
* Provide data to the locationCanSetDifferentSchemeUris-test
*
* @return array
*/
public function locationCanSetDifferentSchemeUrisProvider()
{
return [
['http://www.example.com', Http::class],
['https://www.example.com', Http::class],
['mailto://www.example.com', Mailto::class],
['file://www.example.com', File::class],
];
}
public function testLocationGetFieldValueReturnsProperValue()
{
$locationHeader = new Location();
$locationHeader->setUri('http://www.example.com/');
$this->assertEquals('http://www.example.com/', $locationHeader->getFieldValue());
$locationHeader->setUri('/path');
$this->assertEquals('/path', $locationHeader->getFieldValue());
}
public function testLocationToStringReturnsHeaderFormattedString()
{
$locationHeader = new Location();
$locationHeader->setUri('http://www.example.com/path?query');
$this->assertEquals('Location: http://www.example.com/path?query', $locationHeader->toString());
}
/** Implementation specific tests here */
public function testLocationCanSetAndAccessAbsoluteUri()
{
$locationHeader = Location::fromString('Location: http://www.example.com/path');
$uri = $locationHeader->uri();
$this->assertInstanceOf(Http::class, $uri);
$this->assertTrue($uri->isAbsolute());
$this->assertEquals('http://www.example.com/path', $locationHeader->getUri());
}
public function testLocationCanSetAndAccessRelativeUri()
{
$locationHeader = Location::fromString('Location: /path/to');
$uri = $locationHeader->uri();
$this->assertInstanceOf(Uri::class, $uri);
$this->assertFalse($uri->isAbsolute());
$this->assertEquals('/path/to', $locationHeader->getUri());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testCRLFAttack()
{
$this->expectException(InvalidArgumentException::class);
Location::fromString("Location: http://www.example.com/path\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/RefreshTest.php | test/Header/RefreshTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\Refresh;
class RefreshTest extends TestCase
{
public function testRefreshFromStringCreatesValidRefreshHeader()
{
$refreshHeader = Refresh::fromString('Refresh: xxx');
$this->assertInstanceOf(HeaderInterface::class, $refreshHeader);
$this->assertInstanceOf(Refresh::class, $refreshHeader);
}
public function testRefreshGetFieldNameReturnsHeaderName()
{
$refreshHeader = new Refresh();
$this->assertEquals('Refresh', $refreshHeader->getFieldName());
}
public function testRefreshGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('Refresh needs to be completed');
$refreshHeader = new Refresh();
$this->assertEquals('xxx', $refreshHeader->getFieldValue());
}
public function testRefreshToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('Refresh needs to be completed');
$refreshHeader = new Refresh();
// @todo set some values, then test output
$this->assertEmpty('Refresh: xxx', $refreshHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Refresh::fromString("Refresh: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructorValue()
{
$this->expectException(InvalidArgumentException::class);
new Refresh("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ProxyAuthenticateTest.php | test/Header/ProxyAuthenticateTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\ProxyAuthenticate;
class ProxyAuthenticateTest extends TestCase
{
public function testProxyAuthenticateFromStringCreatesValidProxyAuthenticateHeader()
{
$proxyAuthenticateHeader = ProxyAuthenticate::fromString('Proxy-Authenticate: xxx');
$this->assertInstanceOf(HeaderInterface::class, $proxyAuthenticateHeader);
$this->assertInstanceOf(ProxyAuthenticate::class, $proxyAuthenticateHeader);
}
public function testProxyAuthenticateGetFieldNameReturnsHeaderName()
{
$proxyAuthenticateHeader = new ProxyAuthenticate();
$this->assertEquals('Proxy-Authenticate', $proxyAuthenticateHeader->getFieldName());
}
public function testProxyAuthenticateGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('ProxyAuthenticate needs to be completed');
$proxyAuthenticateHeader = new ProxyAuthenticate();
$this->assertEquals('xxx', $proxyAuthenticateHeader->getFieldValue());
}
public function testProxyAuthenticateToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('ProxyAuthenticate needs to be completed');
$proxyAuthenticateHeader = new ProxyAuthenticate();
// @todo set some values, then test output
$this->assertEmpty('Proxy-Authenticate: xxx', $proxyAuthenticateHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ProxyAuthenticate::fromString("Proxy-Authenticate: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new ProxyAuthenticate("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/FeaturePolicyTest.php | test/Header/FeaturePolicyTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2019 Zend Technologies USA Inc. (https://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\FeaturePolicy;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class FeaturePolicyTest extends TestCase
{
public function testFeaturePolicyFromStringThrowsExceptionIfImproperHeaderNameUsed()
{
$this->expectException(InvalidArgumentException::class);
FeaturePolicy::fromString('X-Feature-Policy: geolocation \'none\';');
}
public function testFeaturePolicyFromStringParsesDirectivesCorrectly()
{
$header = FeaturePolicy::fromString(
"Feature-Policy: geolocation 'none'; autoplay 'self'; microphone 'self';"
);
$this->assertInstanceOf(HeaderInterface::class, $header);
$this->assertInstanceOf(FeaturePolicy::class, $header);
$directives = [
'geolocation' => "'none'",
'autoplay' => "'self'",
'microphone' => "'self'",
];
$this->assertEquals($directives, $header->getDirectives());
}
public function testFeaturePolicyGetFieldNameReturnsHeaderName()
{
$header = new FeaturePolicy();
$this->assertEquals('Feature-Policy', $header->getFieldName());
}
public function testFeaturePolicyToStringReturnsHeaderFormattedString()
{
$header = FeaturePolicy::fromString(
"Feature-Policy: geolocation 'none'; autoplay 'self'; microphone 'self';"
);
$this->assertInstanceOf(HeaderInterface::class, $header);
$this->assertInstanceOf(FeaturePolicy::class, $header);
$this->assertEquals(
"Feature-Policy: geolocation 'none'; autoplay 'self'; microphone 'self';",
$header->toString()
);
}
public function testFeaturePolicySetDirective()
{
$fp = new FeaturePolicy();
$fp->setDirective('geolocation', ['https://*.google.com', 'http://foo.com'])
->setDirective('autoplay', ["'self'"])
->setDirective('microphone', ['https://*.googleapis.com', 'https://*.bar.com']);
$header = 'Feature-Policy: geolocation https://*.google.com http://foo.com; '
. 'autoplay \'self\'; microphone https://*.googleapis.com https://*.bar.com;';
$this->assertEquals($header, $fp->toString());
}
public function testFeaturePolicySetDirectiveWithEmptySourcesDefaultsToNone()
{
$header = new FeaturePolicy();
$header->setDirective('geolocation', ["'self'"])
->setDirective('autoplay', ['*'])
->setDirective('microphone', []);
$this->assertEquals(
"Feature-Policy: geolocation 'self'; autoplay *; microphone 'none';",
$header->toString()
);
}
public function testFeaturePolicySetDirectiveThrowsExceptionIfInvalidDirectiveNameGiven()
{
$this->expectException(InvalidArgumentException::class);
$header = new FeaturePolicy();
$header->setDirective('foo', []);
}
public function testFeaturePolicyGetFieldValueReturnsProperValue()
{
$header = new FeaturePolicy();
$header->setDirective('geolocation', ["'self'"])
->setDirective('microphone', ['https://*.github.com']);
$this->assertEquals("geolocation 'self'; microphone https://*.github.com;", $header->getFieldValue());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
FeaturePolicy::fromString("Feature-Policy: default-src 'none'\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaDirective()
{
$header = new FeaturePolicy();
$this->expectException(InvalidArgumentException::class);
$header->setDirective('default-src', ["\rsome\r\nCRLF\ninjection"]);
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentDispositionTest.php | test/Header/ContentDispositionTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\ContentDisposition;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class ContentDispositionTest extends TestCase
{
public function testContentDispositionFromStringCreatesValidContentDispositionHeader()
{
$contentDispositionHeader = ContentDisposition::fromString('Content-Disposition: xxx');
$this->assertInstanceOf(HeaderInterface::class, $contentDispositionHeader);
$this->assertInstanceOf(ContentDisposition::class, $contentDispositionHeader);
}
public function testContentDispositionGetFieldNameReturnsHeaderName()
{
$contentDispositionHeader = new ContentDisposition();
$this->assertEquals('Content-Disposition', $contentDispositionHeader->getFieldName());
}
public function testContentDispositionGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('ContentDisposition needs to be completed');
$contentDispositionHeader = new ContentDisposition();
$this->assertEquals('xxx', $contentDispositionHeader->getFieldValue());
}
public function testContentDispositionToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('ContentDisposition needs to be completed');
$contentDispositionHeader = new ContentDisposition();
// @todo set some values, then test output
$this->assertEmpty('Content-Disposition: xxx', $contentDispositionHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ContentDisposition::fromString("Content-Disposition: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new ContentDisposition("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/PragmaTest.php | test/Header/PragmaTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\Pragma;
class PragmaTest extends TestCase
{
public function testPragmaFromStringCreatesValidPragmaHeader()
{
$pragmaHeader = Pragma::fromString('Pragma: xxx');
$this->assertInstanceOf(HeaderInterface::class, $pragmaHeader);
$this->assertInstanceOf(Pragma::class, $pragmaHeader);
}
public function testPragmaGetFieldNameReturnsHeaderName()
{
$pragmaHeader = new Pragma();
$this->assertEquals('Pragma', $pragmaHeader->getFieldName());
}
public function testPragmaGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('Pragma needs to be completed');
$pragmaHeader = new Pragma();
$this->assertEquals('xxx', $pragmaHeader->getFieldValue());
}
public function testPragmaToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('Pragma needs to be completed');
$pragmaHeader = new Pragma();
// @todo set some values, then test output
$this->assertEmpty('Pragma: xxx', $pragmaHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Pragma::fromString("Pragma: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new Pragma("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AcceptRangesTest.php | test/Header/AcceptRangesTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\AcceptRanges;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class AcceptRangesTest extends TestCase
{
public function testAcceptRangesFromStringCreatesValidAcceptRangesHeader()
{
$acceptRangesHeader = AcceptRanges::fromString('Accept-Ranges: bytes');
$this->assertInstanceOf(HeaderInterface::class, $acceptRangesHeader);
$this->assertInstanceOf(AcceptRanges::class, $acceptRangesHeader);
}
public function testAcceptRangesGetFieldNameReturnsHeaderName()
{
$acceptRangesHeader = new AcceptRanges();
$this->assertEquals('Accept-Ranges', $acceptRangesHeader->getFieldName());
}
public function testAcceptRangesGetFieldValueReturnsProperValue()
{
$acceptRangesHeader = AcceptRanges::fromString('Accept-Ranges: bytes');
$this->assertEquals('bytes', $acceptRangesHeader->getFieldValue());
$this->assertEquals('bytes', $acceptRangesHeader->getRangeUnit());
}
public function testAcceptRangesToStringReturnsHeaderFormattedString()
{
$acceptRangesHeader = new AcceptRanges();
$acceptRangesHeader->setRangeUnit('bytes');
// @todo set some values, then test output
$this->assertEquals('Accept-Ranges: bytes', $acceptRangesHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
$header = AcceptRanges::fromString("Accept-Ranges: bytes;\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
$header = new AcceptRanges("bytes;\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentRangeTest.php | test/Header/ContentRangeTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\ContentRange;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class ContentRangeTest extends TestCase
{
public function testContentRangeFromStringCreatesValidContentRangeHeader()
{
$contentRangeHeader = ContentRange::fromString('Content-Range: xxx');
$this->assertInstanceOf(HeaderInterface::class, $contentRangeHeader);
$this->assertInstanceOf(ContentRange::class, $contentRangeHeader);
}
public function testContentRangeGetFieldNameReturnsHeaderName()
{
$contentRangeHeader = new ContentRange();
$this->assertEquals('Content-Range', $contentRangeHeader->getFieldName());
}
public function testContentRangeGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('ContentRange needs to be completed');
$contentRangeHeader = new ContentRange();
$this->assertEquals('xxx', $contentRangeHeader->getFieldValue());
}
public function testContentRangeToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('ContentRange needs to be completed');
$contentRangeHeader = new ContentRange();
// @todo set some values, then test output
$this->assertEmpty('Content-Range: xxx', $contentRangeHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ContentRange::fromString("Content-Range: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new ContentRange("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ConnectionTest.php | test/Header/ConnectionTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Connection;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class ConnectionTest extends TestCase
{
public function testConnectionFromStringCreatesValidConnectionHeader()
{
$connectionHeader = Connection::fromString('Connection: close');
$this->assertInstanceOf(HeaderInterface::class, $connectionHeader);
$this->assertInstanceOf(Connection::class, $connectionHeader);
$this->assertEquals('close', $connectionHeader->getFieldValue());
$this->assertFalse($connectionHeader->isPersistent());
}
public function testConnectionGetFieldNameReturnsHeaderName()
{
$connectionHeader = new Connection();
$this->assertEquals('Connection', $connectionHeader->getFieldName());
}
public function testConnectionGetFieldValueReturnsProperValue()
{
$connectionHeader = new Connection();
$connectionHeader->setValue('Keep-Alive');
$this->assertEquals('keep-alive', $connectionHeader->getFieldValue());
}
public function testConnectionToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('Connection needs to be completed');
$connectionHeader = new Connection();
$connectionHeader->setValue('close');
$this->assertEmpty('Connection: close', $connectionHeader->toString());
}
public function testConnectionSetPersistentReturnsProperValue()
{
$connectionHeader = new Connection();
$connectionHeader->setPersistent(true);
$this->assertEquals('keep-alive', $connectionHeader->getFieldValue());
$connectionHeader->setPersistent(false);
$this->assertEquals('close', $connectionHeader->getFieldValue());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Connection::fromString("Connection: close\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaSetters()
{
$header = new Connection();
$this->expectException(InvalidArgumentException::class);
$header->setValue("close\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AcceptCharsetTest.php | test/Header/AcceptCharsetTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\AcceptCharset;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class AcceptCharsetTest extends TestCase
{
public function testAcceptCharsetFromStringCreatesValidAcceptCharsetHeader()
{
$acceptCharsetHeader = AcceptCharset::fromString('Accept-Charset: xxx');
$this->assertInstanceOf(HeaderInterface::class, $acceptCharsetHeader);
$this->assertInstanceOf(AcceptCharset::class, $acceptCharsetHeader);
}
public function testAcceptCharsetGetFieldNameReturnsHeaderName()
{
$acceptCharsetHeader = new AcceptCharset();
$this->assertEquals('Accept-Charset', $acceptCharsetHeader->getFieldName());
}
public function testAcceptCharsetGetFieldValueReturnsProperValue()
{
$acceptCharsetHeader = AcceptCharset::fromString('Accept-Charset: xxx');
$this->assertEquals('xxx', $acceptCharsetHeader->getFieldValue());
}
public function testAcceptCharsetGetFieldValueReturnsProperValueWithTrailingSemicolon()
{
$acceptCharsetHeader = AcceptCharset::fromString('Accept-Charset: xxx;');
$this->assertEquals('xxx', $acceptCharsetHeader->getFieldValue());
}
public function testAcceptCharsetGetFieldValueReturnsProperValueWithSemicolonWithoutEqualSign()
{
$acceptCharsetHeader = AcceptCharset::fromString('Accept-Charset: xxx;yyy');
$this->assertEquals('xxx;yyy', $acceptCharsetHeader->getFieldValue());
}
public function testAcceptCharsetToStringReturnsHeaderFormattedString()
{
$acceptCharsetHeader = new AcceptCharset();
$acceptCharsetHeader->addCharset('iso-8859-5', 0.8)
->addCharset('unicode-1-1', 1);
$this->assertEquals('Accept-Charset: iso-8859-5;q=0.8, unicode-1-1', $acceptCharsetHeader->toString());
}
/** Implementation specific tests here */
public function testCanParseCommaSeparatedValues()
{
$header = AcceptCharset::fromString('Accept-Charset: iso-8859-5;q=0.8,unicode-1-1');
$this->assertTrue($header->hasCharset('iso-8859-5'));
$this->assertTrue($header->hasCharset('unicode-1-1'));
}
public function testPrioritizesValuesBasedOnQParameter()
{
$header = AcceptCharset::fromString('Accept-Charset: iso-8859-5;q=0.8,unicode-1-1,*;q=0.4');
$expected = [
'unicode-1-1',
'iso-8859-5',
'*',
];
foreach ($header->getPrioritized() as $type) {
$this->assertEquals(array_shift($expected), $type->getCharset());
}
}
public function testWildcharCharset()
{
$acceptHeader = new AcceptCharset();
$acceptHeader->addCharset('iso-8859-5', 0.8)
->addCharset('*', 0.4);
$this->assertTrue($acceptHeader->hasCharset('iso-8859-5'));
$this->assertTrue($acceptHeader->hasCharset('unicode-1-1'));
$this->assertEquals('Accept-Charset: iso-8859-5;q=0.8, *;q=0.4', $acceptHeader->toString());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
AcceptCharset::fromString("Accept-Charset: iso-8859-5\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaSetters()
{
$header = new AcceptCharset();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('valid type');
$header->addCharset("\niso\r-8859-\r\n5");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/RangeTest.php | test/Header/RangeTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\Range;
class RangeTest extends TestCase
{
public function testRangeFromStringCreatesValidRangeHeader()
{
$rangeHeader = Range::fromString('Range: xxx');
$this->assertInstanceOf(HeaderInterface::class, $rangeHeader);
$this->assertInstanceOf(Range::class, $rangeHeader);
}
public function testRangeGetFieldNameReturnsHeaderName()
{
$rangeHeader = new Range();
$this->assertEquals('Range', $rangeHeader->getFieldName());
}
public function testRangeGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('Range needs to be completed');
$rangeHeader = new Range();
$this->assertEquals('xxx', $rangeHeader->getFieldValue());
}
public function testRangeToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('Range needs to be completed');
$rangeHeader = new Range();
// @todo set some values, then test output
$this->assertEmpty('Range: xxx', $rangeHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Range::fromString("Range: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructorValue()
{
$this->expectException(InvalidArgumentException::class);
new Range("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AllowTest.php | test/Header/AllowTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Allow;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class AllowTest extends TestCase
{
public function testAllowFromStringCreatesValidAllowHeader()
{
$allowHeader = Allow::fromString('Allow: GET, POST, PUT');
$this->assertInstanceOf(HeaderInterface::class, $allowHeader);
$this->assertInstanceOf(Allow::class, $allowHeader);
$this->assertEquals(['GET', 'POST', 'PUT'], $allowHeader->getAllowedMethods());
}
public function testAllowFromStringSupportsExtensionMethods()
{
$allowHeader = Allow::fromString('Allow: GET, POST, PROCREATE');
$this->assertTrue($allowHeader->isAllowedMethod('PROCREATE'));
}
public function testAllowFromStringWithNonPostMethod()
{
$allowHeader = Allow::fromString('Allow: GET');
$this->assertEquals('GET', $allowHeader->getFieldValue());
}
public function testAllowGetFieldNameReturnsHeaderName()
{
$allowHeader = new Allow();
$this->assertEquals('Allow', $allowHeader->getFieldName());
}
public function testAllowListAllDefinedMethods()
{
$methods = [
'OPTIONS' => false,
'GET' => true,
'HEAD' => false,
'POST' => true,
'PUT' => false,
'DELETE' => false,
'TRACE' => false,
'CONNECT' => false,
'PATCH' => false,
];
$allowHeader = new Allow();
$this->assertEquals($methods, $allowHeader->getAllMethods());
}
public function testAllowGetDefaultAllowedMethods()
{
$allowHeader = new Allow();
$this->assertEquals(['GET', 'POST'], $allowHeader->getAllowedMethods());
}
public function testAllowGetFieldValueReturnsProperValue()
{
$allowHeader = new Allow();
$allowHeader->allowMethods(['GET', 'POST', 'TRACE']);
$this->assertEquals('GET, POST, TRACE', $allowHeader->getFieldValue());
}
public function testAllowToStringReturnsHeaderFormattedString()
{
$allowHeader = new Allow();
$allowHeader->allowMethods(['GET', 'POST', 'TRACE']);
$this->assertEquals('Allow: GET, POST, TRACE', $allowHeader->toString());
}
public function testAllowChecksAllowedMethod()
{
$allowHeader = new Allow();
$allowHeader->allowMethods(['GET', 'POST', 'TRACE']);
$this->assertTrue($allowHeader->isAllowedMethod('TRACE'));
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid header value detected');
Allow::fromString("Allow: GET\r\n\r\nevilContent");
}
public function injectionMethods()
{
return [
'string' => ["\rG\r\nE\nT"],
'array' => [["\rG\r\nE\nT"]],
];
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*
* @dataProvider injectionMethods
*
* @param array|string $methods
*/
public function testPreventsCRLFAttackViaAllowMethods($methods)
{
$header = new Allow();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('valid method');
$header->allowMethods($methods);
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*
* @dataProvider injectionMethods
*
* @param array|string $methods
*/
public function testPreventsCRLFAttackViaDisallowMethods($methods)
{
$header = new Allow();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('valid method');
$header->disallowMethods($methods);
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentLocationTest.php | test/Header/ContentLocationTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\ContentLocation;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Uri\UriInterface;
class ContentLocationTest extends TestCase
{
public function testContentLocationFromStringCreatesValidLocationHeader()
{
$contentLocationHeader = ContentLocation::fromString('Content-Location: http://www.example.com/');
$this->assertInstanceOf(HeaderInterface::class, $contentLocationHeader);
$this->assertInstanceOf(ContentLocation::class, $contentLocationHeader);
}
public function testContentLocationGetFieldValueReturnsProperValue()
{
$contentLocationHeader = new ContentLocation();
$contentLocationHeader->setUri('http://www.example.com/');
$this->assertEquals('http://www.example.com/', $contentLocationHeader->getFieldValue());
$contentLocationHeader->setUri('/path');
$this->assertEquals('/path', $contentLocationHeader->getFieldValue());
}
public function testContentLocationToStringReturnsHeaderFormattedString()
{
$contentLocationHeader = new ContentLocation();
$contentLocationHeader->setUri('http://www.example.com/path?query');
$this->assertEquals('Content-Location: http://www.example.com/path?query', $contentLocationHeader->toString());
}
/** Implementation specific tests here */
public function testContentLocationCanSetAndAccessAbsoluteUri()
{
$contentLocationHeader = ContentLocation::fromString('Content-Location: http://www.example.com/path');
$uri = $contentLocationHeader->uri();
$this->assertInstanceOf(UriInterface::class, $uri);
$this->assertTrue($uri->isAbsolute());
$this->assertEquals('http://www.example.com/path', $contentLocationHeader->getUri());
}
public function testContentLocationCanSetAndAccessRelativeUri()
{
$contentLocationHeader = ContentLocation::fromString('Content-Location: /path/to');
$uri = $contentLocationHeader->uri();
$this->assertInstanceOf(UriInterface::class, $uri);
$this->assertFalse($uri->isAbsolute());
$this->assertEquals('/path/to', $contentLocationHeader->getUri());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ContentLocation::fromString("Content-Location: /path/to\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AcceptEncodingTest.php | test/Header/AcceptEncodingTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\AcceptEncoding;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class AcceptEncodingTest extends TestCase
{
public function testAcceptEncodingFromStringCreatesValidAcceptEncodingHeader()
{
$acceptEncodingHeader = AcceptEncoding::fromString('Accept-Encoding: xxx');
$this->assertInstanceOf(HeaderInterface::class, $acceptEncodingHeader);
$this->assertInstanceOf(AcceptEncoding::class, $acceptEncodingHeader);
}
public function testAcceptEncodingGetFieldNameReturnsHeaderName()
{
$acceptEncodingHeader = new AcceptEncoding();
$this->assertEquals('Accept-Encoding', $acceptEncodingHeader->getFieldName());
}
public function testAcceptEncodingGetFieldValueReturnsProperValue()
{
$acceptEncodingHeader = AcceptEncoding::fromString('Accept-Encoding: xxx');
$this->assertEquals('xxx', $acceptEncodingHeader->getFieldValue());
}
public function testAcceptEncodingGetFieldValueReturnsProperValueWithTrailingSemicolon()
{
$acceptEncodingHeader = AcceptEncoding::fromString('Accept-Encoding: xxx;');
$this->assertEquals('xxx', $acceptEncodingHeader->getFieldValue());
}
public function testAcceptEncodingGetFieldValueReturnsProperValueWithSemicolonWithoutEqualSign()
{
$acceptEncodingHeader = AcceptEncoding::fromString('Accept-Encoding: xxx;yyy');
$this->assertEquals('xxx;yyy', $acceptEncodingHeader->getFieldValue());
}
public function testAcceptEncodingToStringReturnsHeaderFormattedString()
{
$acceptEncodingHeader = new AcceptEncoding();
$acceptEncodingHeader->addEncoding('compress', 0.5)
->addEncoding('gzip', 1);
$this->assertEquals('Accept-Encoding: compress;q=0.5, gzip', $acceptEncodingHeader->toString());
}
/** Implementation specific tests here */
public function testCanParseCommaSeparatedValues()
{
$header = AcceptEncoding::fromString('Accept-Encoding: compress;q=0.5,gzip');
$this->assertTrue($header->hasEncoding('compress'));
$this->assertTrue($header->hasEncoding('gzip'));
}
public function testPrioritizesValuesBasedOnQParameter()
{
$header = AcceptEncoding::fromString('Accept-Encoding: compress;q=0.8,gzip,*;q=0.4');
$expected = [
'gzip',
'compress',
'*',
];
$test = [];
foreach ($header->getPrioritized() as $type) {
$this->assertEquals(array_shift($expected), $type->getEncoding());
}
}
public function testWildcharEncoder()
{
$acceptHeader = new AcceptEncoding();
$acceptHeader->addEncoding('compress', 0.8)
->addEncoding('*', 0.4);
$this->assertTrue($acceptHeader->hasEncoding('compress'));
$this->assertTrue($acceptHeader->hasEncoding('gzip'));
$this->assertEquals('Accept-Encoding: compress;q=0.8, *;q=0.4', $acceptHeader->toString());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
$header = AcceptEncoding::fromString("Accept-Encoding: compress\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaSetters()
{
$header = new AcceptEncoding();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('valid type');
$header->addEncoding("\nc\rom\r\npress");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AcceptLanguageTest.php | test/Header/AcceptLanguageTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\AcceptLanguage;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class AcceptLanguageTest extends TestCase
{
public function testAcceptLanguageFromStringCreatesValidAcceptLanguageHeader()
{
$acceptLanguageHeader = AcceptLanguage::fromString('Accept-Language: xxx');
$this->assertInstanceOf(HeaderInterface::class, $acceptLanguageHeader);
$this->assertInstanceOf(AcceptLanguage::class, $acceptLanguageHeader);
}
public function testAcceptLanguageGetFieldNameReturnsHeaderName()
{
$acceptLanguageHeader = new AcceptLanguage();
$this->assertEquals('Accept-Language', $acceptLanguageHeader->getFieldName());
}
public function testAcceptLanguageGetFieldValueReturnsProperValue()
{
$acceptLanguageHeader = AcceptLanguage::fromString('Accept-Language: xxx');
$this->assertEquals('xxx', $acceptLanguageHeader->getFieldValue());
}
public function testAcceptLanguageGetFieldValueReturnsProperValueWithTrailingSemicolon()
{
$acceptLanguageHeader = AcceptLanguage::fromString('Accept-Language: xxx;');
$this->assertEquals('xxx', $acceptLanguageHeader->getFieldValue());
}
public function testAcceptLanguageGetFieldValueReturnsProperValueWithSemicolonWithoutEqualSign()
{
$acceptLanguageHeader = AcceptLanguage::fromString('Accept-Language: xxx;yyy');
$this->assertEquals('xxx;yyy', $acceptLanguageHeader->getFieldValue());
}
public function testAcceptLanguageToStringReturnsHeaderFormattedString()
{
$acceptLanguageHeader = new AcceptLanguage();
$acceptLanguageHeader->addLanguage('da', 0.8)
->addLanguage('en-gb', 1);
$this->assertEquals('Accept-Language: da;q=0.8, en-gb', $acceptLanguageHeader->toString());
}
/** Implementation specific tests here */
public function testCanParseCommaSeparatedValues()
{
$header = AcceptLanguage::fromString('Accept-Language: da;q=0.8, en-gb');
$this->assertTrue($header->hasLanguage('da'));
$this->assertTrue($header->hasLanguage('en-gb'));
}
public function testPrioritizesValuesBasedOnQParameter()
{
$header = AcceptLanguage::fromString('Accept-Language: da;q=0.8, en-gb, *;q=0.4');
$expected = [
'en-gb',
'da',
'*',
];
$test = [];
foreach ($header->getPrioritized() as $type) {
$this->assertEquals(array_shift($expected), $type->typeString);
}
$this->assertEquals($expected, $test);
}
public function testWildcharLanguage()
{
$acceptHeader = new AcceptLanguage();
$acceptHeader->addLanguage('da', 0.8)
->addLanguage('*', 0.4);
$this->assertTrue($acceptHeader->hasLanguage('da'));
$this->assertTrue($acceptHeader->hasLanguage('en'));
$this->assertEquals('Accept-Language: da;q=0.8, *;q=0.4', $acceptHeader->toString());
}
public function testWildcards()
{
$accept = AcceptLanguage::fromString('*, en-*, en-us');
$res = $accept->getPrioritized();
$this->assertEquals('en-us', $res[0]->getLanguage());
$this->assertEquals('en', $res[0]->getPrimaryTag());
$this->assertEquals('us', $res[0]->getSubTag());
$this->assertEquals('en-*', $res[1]->getLanguage());
$this->assertEquals('en', $res[1]->getPrimaryTag());
$this->assertTrue($accept->hasLanguage('nl'));
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
$header = AcceptLanguage::fromString("Accept-Language: da\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaSetters()
{
$header = new AcceptLanguage();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('valid type');
$header->addLanguage("\nen\r-\r\nus");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/DateTest.php | test/Header/DateTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use DateTime;
use DateTimeZone;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Date;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class DateTest extends TestCase
{
public function tearDown()
{
// set to RFC default date format
Date::setDateFormat(Date::DATE_RFC1123);
}
public function testDateFromStringCreatesValidDateHeader()
{
$dateHeader = Date::fromString('Date: Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertInstanceOf(HeaderInterface::class, $dateHeader);
$this->assertInstanceOf(Date::class, $dateHeader);
}
public function testDateFromTimeStringCreatesValidDateHeader()
{
$dateHeader = Date::fromTimeString('+12 hours');
$this->assertInstanceOf(HeaderInterface::class, $dateHeader);
$this->assertInstanceOf(Date::class, $dateHeader);
$date = new DateTime(null, new DateTimeZone('GMT'));
$interval = $dateHeader->date()->diff($date, 1);
if (PHP_VERSION_ID >= 70200) {
$this->assertSame('+11 hours 59 minutes 59 seconds', $interval->format('%R%H hours %I minutes %S seconds'));
$this->assertLessThan(1, $interval->f);
$this->assertGreaterThan(0, $interval->f);
} else {
$this->assertSame('+12 hours 00 minutes 00 seconds', $interval->format('%R%H hours %I minutes %S seconds'));
}
}
public function testDateFromTimestampCreatesValidDateHeader()
{
$dateHeader = Date::fromTimestamp(time() + 12 * 60 * 60);
$this->assertInstanceOf(HeaderInterface::class, $dateHeader);
$this->assertInstanceOf(Date::class, $dateHeader);
$date = new DateTime(null, new DateTimeZone('GMT'));
$interval = $dateHeader->date()->diff($date, 1);
if (PHP_VERSION_ID >= 70200) {
$this->assertSame('+11 hours 59 minutes 59 seconds', $interval->format('%R%H hours %I minutes %S seconds'));
$this->assertLessThan(1, $interval->f);
$this->assertGreaterThan(0, $interval->f);
} else {
$this->assertSame('+12 hours 00 minutes 00 seconds', $interval->format('%R%H hours %I minutes %S seconds'));
}
}
public function testDateFromTimeStringDetectsBadInput()
{
$this->expectException(InvalidArgumentException::class);
Date::fromTimeString('3 Days of the Condor');
}
public function testDateFromTimestampDetectsBadInput()
{
$this->expectException(InvalidArgumentException::class);
Date::fromTimestamp('The Day of the Jackal');
}
public function testDateGetFieldNameReturnsHeaderName()
{
$dateHeader = new Date();
$this->assertEquals('Date', $dateHeader->getFieldName());
}
public function testDateGetFieldValueReturnsProperValue()
{
$dateHeader = new Date();
$dateHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $dateHeader->getFieldValue());
}
public function testDateToStringReturnsHeaderFormattedString()
{
$dateHeader = new Date();
$dateHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Date: Sun, 06 Nov 1994 08:49:37 GMT', $dateHeader->toString());
}
/** Implementation specific tests here */
public function testDateReturnsDateTimeObject()
{
$dateHeader = new Date();
$this->assertInstanceOf(DateTime::class, $dateHeader->date());
}
public function testDateFromStringCreatesValidDateTime()
{
$dateHeader = Date::fromString('Date: Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertInstanceOf(DateTime::class, $dateHeader->date());
$this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $dateHeader->date()->format('D, d M Y H:i:s \G\M\T'));
}
public function testDateReturnsProperlyFormattedDate()
{
$date = new DateTime('now', new DateTimeZone('GMT'));
$dateHeader = new Date();
$dateHeader->setDate($date);
$this->assertEquals($date->format('D, d M Y H:i:s \G\M\T'), $dateHeader->getDate());
}
public function testDateThrowsExceptionForInvalidDate()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid date');
$dateHeader = new Date();
$dateHeader->setDate('~~~~');
}
public function testDateCanCompareDates()
{
$dateHeader = new Date();
$dateHeader->setDate('1 day ago');
$this->assertEquals(-1, $dateHeader->compareTo(new DateTime('now')));
}
public function testDateCanOutputDatesInOldFormats()
{
Date::setDateFormat(Date::DATE_ANSIC);
$dateHeader = new Date();
$dateHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Date: Sun Nov 6 08:49:37 1994', $dateHeader->toString());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Date::fromString("Date: Sun, 06 Nov 1994 08:49:37 GMT\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/EtagTest.php | test/Header/EtagTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Etag;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class EtagTest extends TestCase
{
public function testEtagFromStringCreatesValidEtagHeader()
{
$etagHeader = Etag::fromString('Etag: xxx');
$this->assertInstanceOf(HeaderInterface::class, $etagHeader);
$this->assertInstanceOf(Etag::class, $etagHeader);
}
public function testEtagGetFieldNameReturnsHeaderName()
{
$etagHeader = new Etag();
$this->assertEquals('Etag', $etagHeader->getFieldName());
}
public function testEtagGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('Etag needs to be completed');
$etagHeader = new Etag();
$this->assertEquals('xxx', $etagHeader->getFieldValue());
}
public function testEtagToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('Etag needs to be completed');
$etagHeader = new Etag();
// @todo set some values, then test output
$this->assertEmpty('Etag: xxx', $etagHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Etag::fromString("Etag: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new Etag("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/HostTest.php | test/Header/HostTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\Host;
class HostTest extends TestCase
{
public function testHostFromStringCreatesValidHostHeader()
{
$hostHeader = Host::fromString('Host: xxx');
$this->assertInstanceOf(HeaderInterface::class, $hostHeader);
$this->assertInstanceOf(Host::class, $hostHeader);
}
public function testHostGetFieldNameReturnsHeaderName()
{
$hostHeader = new Host();
$this->assertEquals('Host', $hostHeader->getFieldName());
}
public function testHostGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('Host needs to be completed');
$hostHeader = new Host();
$this->assertEquals('xxx', $hostHeader->getFieldValue());
}
public function testHostToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('Host needs to be completed');
$hostHeader = new Host();
// @todo set some values, then test output
$this->assertEmpty('Host: xxx', $hostHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Host::fromString("Host: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new Host("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AcceptTest.php | test/Header/AcceptTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Accept;
use Zend\Http\Header\Accept\FieldValuePart\AbstractFieldValuePart;
use Zend\Http\Header\Accept\FieldValuePart\AcceptFieldValuePart;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class AcceptTest extends TestCase
{
public function testInvalidHeaderLine()
{
$this->expectException(InvalidArgumentException::class);
Accept::fromString('');
}
public function testAcceptFromStringCreatesValidAcceptHeader()
{
$acceptHeader = Accept::fromString('Accept: xxx');
$this->assertInstanceOf(HeaderInterface::class, $acceptHeader);
$this->assertInstanceOf(Accept::class, $acceptHeader);
}
public function testAcceptGetFieldNameReturnsHeaderName()
{
$acceptHeader = new Accept();
$this->assertEquals('Accept', $acceptHeader->getFieldName());
}
public function testAcceptGetFieldValueReturnsProperValue()
{
$acceptHeader = Accept::fromString('Accept: xxx');
$this->assertEquals('xxx', $acceptHeader->getFieldValue());
}
public function testAcceptGetFieldValueReturnsProperValueWithAHeaderWithoutSpaces()
{
$acceptHeader = Accept::fromString('Accept:xxx');
$this->assertEquals('xxx', $acceptHeader->getFieldValue());
}
public function testAcceptToStringReturnsHeaderFormattedString()
{
$acceptHeader = new Accept();
$acceptHeader->addMediaType('text/html', 0.8)
->addMediaType('application/json', 1)
->addMediaType('application/atom+xml', 0.9);
// @todo set some values, then test output
$this->assertEquals(
'Accept: text/html;q=0.8, application/json, application/atom+xml;q=0.9',
$acceptHeader->toString()
);
$this->expectException(InvalidArgumentException::class);
$acceptHeader->addMediaType('\\', 0.9);
}
/** Implementation specific tests here */
public function testCanParseCommaSeparatedValues()
{
$header = Accept::fromString('Accept: text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c');
$this->assertTrue($header->hasMediaType('text/plain'));
$this->assertTrue($header->hasMediaType('text/html'));
$this->assertTrue($header->hasMediaType('text/x-dvi'));
$this->assertTrue($header->hasMediaType('text/x-c'));
}
public function testPrioritizesValuesBasedOnQParameter()
{
$header = Accept::fromString(
'Accept: text/plain; q=0.5, text/html, text/xml; q=0, text/x-dvi; q=0.8, text/x-c'
);
$expected = [
'text/html',
'text/x-c',
'text/x-dvi',
'text/plain',
'text/xml',
];
foreach ($header->getPrioritized() as $type) {
$this->assertEquals(array_shift($expected), $type->typeString);
}
}
public function testLevel()
{
$acceptHeader = new Accept();
$acceptHeader->addMediaType('text/html', 0.8, ['level' => 1])
->addMediaType('text/html', 0.4, ['level' => 2])
->addMediaType('application/atom+xml', 0.9);
$this->assertEquals(
'Accept: text/html;q=0.8;level=1, '
. 'text/html;q=0.4;level=2, application/atom+xml;q=0.9',
$acceptHeader->toString()
);
}
public function testPrioritizedLevel()
{
$header = Accept::fromString(
'Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1,'
. 'text/html;level=2;q=0.4, */*;q=0.5'
);
$expected = [
'text/html;level=1',
'text/html;q=0.7',
'*/*;q=0.5',
'text/html;level=2;q=0.4',
'text/*;q=0.3',
];
foreach ($header->getPrioritized() as $type) {
$this->assertEquals(array_shift($expected), $type->raw);
}
}
public function testPrios()
{
$values = [
'invalidPrio' => false,
-0.0001 => false,
1.0001 => false,
1.000 => true,
0.999 => true,
0.000 => true,
0.001 => true,
1 => true,
0 => true,
];
$header = new Accept();
foreach ($values as $prio => $shouldPass) {
try {
$header->addMediaType('text/html', $prio);
if (! $shouldPass) {
$this->fail('Exception expected');
}
} catch (InvalidArgumentException $e) {
if ($shouldPass) {
throw $e;
}
}
}
}
public function testWildcharMediaType()
{
$acceptHeader = new Accept();
$acceptHeader->addMediaType('text/*', 0.8)
->addMediaType('application/*', 1)
->addMediaType('*/*', 0.4);
$this->assertTrue($acceptHeader->hasMediaType('text/html'));
$this->assertTrue($acceptHeader->hasMediaType('application/atom+xml'));
$this->assertTrue($acceptHeader->hasMediaType('audio/basic'));
$this->assertEquals('Accept: application/*, text/*;q=0.8, */*;q=0.4', $acceptHeader->toString());
}
public function testMatchWildCard()
{
$acceptHeader = Accept::fromString('Accept: */*');
$this->assertTrue($acceptHeader->hasMediaType('application/vnd.foobar+json'));
$acceptHeader = Accept::fromString('Accept: application/*');
$this->assertTrue($acceptHeader->hasMediaType('application/vnd.foobar+json'));
$this->assertTrue($acceptHeader->hasMediaType('application/vnd.foobar+*'));
$acceptHeader = Accept::fromString('Accept: application/vnd.foobar+html');
$this->assertTrue($acceptHeader->hasMediaType('*/html'));
$this->assertTrue($acceptHeader->hasMediaType('application/vnd.foobar+*'));
$acceptHeader = Accept::fromString('Accept: text/html');
$this->assertTrue($acceptHeader->hasMediaType('*/html'));
$this->assertTrue($acceptHeader->hasMediaType('*/*+html'));
$this->assertTrue($acceptHeader->hasMediaType('text/*'));
}
public function testParsingAndAssemblingQuotedStrings()
{
$acceptStr = 'Accept: application/vnd.foobar+html;q=1;version="2'
. '\"";level="foo;, bar", text/json;level=1, text/xml;level=2;q=0.4';
$acceptHeader = Accept::fromString($acceptStr);
$this->assertEquals($acceptStr, $acceptHeader->getFieldName() . ': ' . $acceptHeader->getFieldValue());
}
public function testMatchReturnsMatchedAgainstObject()
{
$acceptStr = 'Accept: text/html;q=1; version=23; level=5, text/json;level=1,text/xml;level=2;q=0.4';
$acceptHeader = Accept::fromString($acceptStr);
$res = $acceptHeader->match('text/html; _randomValue=foobar');
$this->assertInstanceOf(AbstractFieldValuePart::class, $res->getMatchedAgainst());
$this->assertEquals(
'foobar',
$res->getMatchedAgainst()->getParams()->_randomValue
);
$acceptStr = 'Accept: */*; ';
$acceptHeader = Accept::fromString($acceptStr);
$res = $acceptHeader->match('text/html; _foo=bar');
$this->assertInstanceOf(AbstractFieldValuePart::class, $res->getMatchedAgainst());
$this->assertEquals(
'bar',
$res->getMatchedAgainst()->getParams()->_foo
);
}
public function testVersioning()
{
$acceptStr = 'Accept: text/html;q=1; version=23; level=5, text/json;level=1,text/xml;level=2;q=0.4';
$acceptHeader = Accept::fromString($acceptStr);
$expected = [
'typeString' => 'text/html',
'type' => 'text',
'subtype' => 'html',
'subtypeRaw' => 'html',
'format' => 'html',
'priority' => 1,
'params' => ['q' => 1, 'version' => 23, 'level' => 5],
'raw' => 'text/html;q=1; version=23; level=5',
];
$this->assertFalse($acceptHeader->match('text/html; version=22'));
$res = $acceptHeader->match('text/html; version=23');
foreach ($expected as $key => $value) {
$this->assertEquals($value, $res->$key);
}
$this->assertFalse($acceptHeader->match('text/html; version=24'));
$res = $acceptHeader->match('text/html; version=22-24');
foreach ($expected as $key => $value) {
$this->assertEquals($value, $res->$key);
}
$this->assertFalse($acceptHeader->match('text/html; version=20|22|24'));
$res = $acceptHeader->match('text/html; version=22|23|24');
foreach ($expected as $key => $value) {
$this->assertEquals($value, $res->$key);
}
}
public function testWildcardWithDifferentParamsAndRanges()
{
$acceptHeader = Accept::fromString('Accept: */*; version=21');
$this->assertFalse($acceptHeader->match('*/*; version=20|22'));
$acceptHeader = Accept::fromString('Accept: */*; version=19');
$this->assertFalse($acceptHeader->match('*/*; version=20-22'));
$acceptHeader = Accept::fromString('Accept: */*; version=23');
$this->assertFalse($acceptHeader->match('*/*; version=20-22'));
$acceptHeader = Accept::fromString('Accept: */*; version=21');
$res = $acceptHeader->match('*/*; version=20-22');
$this->assertInstanceOf(AcceptFieldValuePart::class, $res);
$this->assertEquals('21', $res->getParams()->version);
}
/**
* @group 3739
* @covers Zend\Http\Header\AbstractAccept::matchAcceptParams()
*/
public function testParamRangesWithDecimals()
{
$acceptHeader = Accept::fromString('Accept: application/vnd.com.example+xml; version=10');
$this->assertFalse($acceptHeader->match('application/vnd.com.example+xml; version="\"3.1\"-\"3.1.1-DEV\""'));
}
/**
* @group 3740
* @covers Zend\Http\Header\AbstractAccept::matchAcceptParams()
* @covers Zend\Http\Header\AbstractAccept::getParametersFromFieldValuePart()
*
* @dataProvider provideParamRanges
*
* @param string $range
* @param string $input
* @param bool $success
*/
public function testParamRangesSupportDevStage($range, $input, $success)
{
$acceptHeader = Accept::fromString(
'Accept: application/vnd.com.example+xml; version="' . addslashes($input) . '"'
);
$res = $acceptHeader->match(
'application/vnd.com.example+xml; version="' . addslashes($range) . '"'
);
if ($success) {
$this->assertInstanceOf(AcceptFieldValuePart::class, $res);
} else {
$this->assertFalse($res);
}
}
/**
* @group 3740
* @return array
*/
public function provideParamRanges()
{
return [
['"3.1.1-DEV"-3.1.1', '3.1.1', true],
['3.1.0-"3.1.1-DEV"', '3.1.1', false],
['3.1.0-"3.1.1-DEV"', '3.1.1-DEV', true],
['3.1.0-"3.1.1-DEV"', '3.1.2-DEV', false],
['3.1.0-"3.1.1"', '3.1.2-DEV', false],
['3.1.0-"3.1.1"', '3.1.0-DEV', false],
['"3.1.0-DEV"-"3.1.1-BETA"', '3.1.0', true],
['"3.1.0-DEV"-"3.1.1-BETA"', '3.1.1', false],
['"3.1.0-DEV"-"3.1.1-BETA"', '3.1.1-BETA', true],
['"3.1.0-DEV"-"3.1.1-BETA"', '3.1.0-DEV', true],
];
}
public function testVersioningAndPriorization()
{
$acceptStr = 'Accept: text/html; version=23, text/json; version=15.3; q=0.9,text/html;level=2;q=0.4';
$acceptHeader = Accept::fromString($acceptStr);
$expected = [
'typeString' => 'text/json',
'type' => 'text',
'subtype' => 'json',
'subtypeRaw' => 'json',
'format' => 'json',
'priority' => 0.9,
'params' => ['q' => 0.9, 'version' => 15.3],
'raw' => 'text/json; version=15.3; q=0.9',
];
$str = 'text/html; version=17, text/json; version=15-16';
$res = $acceptHeader->match($str);
foreach ($expected as $key => $value) {
$this->assertEquals($value, $res->$key);
}
$expected = (object) [
'typeString' => 'text/html',
'type' => 'text',
'subtype' => 'html',
'subtypeRaw' => 'html',
'format' => 'html',
'priority' => 0.4,
'params' => ['q' => 0.4, 'level' => 2],
'raw' => 'text/html;level=2;q=0.4',
];
$str = 'text/html; version=17,text/json; version=15-16; q=0.5';
$res = $acceptHeader->match($str);
foreach ($expected as $key => $value) {
$this->assertEquals($value, $res->$key);
}
}
public function testPrioritizing()
{
// Example is copy/paste from rfc2616
$acceptStr = 'Accept: text/*;q=0.3, */*,text/html;q=1, text/html;level=1,text/html;level=2;q=0.4, */*;q=0.5';
$acceptHdr = Accept::fromString($acceptStr);
$expected = [
'typeString' => 'text/html',
'type' => 'text',
'subtype' => 'html',
'subtypeRaw' => 'html',
'format' => 'html',
'priority' => 1,
'params' => ['level' => 1],
'raw' => 'text/html;level=1',
];
$res = $acceptHdr->match('text/html');
foreach ($expected as $key => $value) {
$this->assertEquals($value, $res->$key);
}
$res = $acceptHdr->match('text');
foreach ($expected as $key => $value) {
$this->assertEquals($value, $res->$key);
}
}
public function testPrioritizing2()
{
$accept = Accept::fromString("Accept: application/text, \tapplication/*");
$res = $accept->getPrioritized();
$this->assertEquals('application/text', $res[0]->raw);
$this->assertEquals('application/*', $res[1]->raw);
$accept = Accept::fromString("Accept: \tapplication/*, application/text");
$res = $accept->getPrioritized();
$this->assertEquals('application/text', $res[0]->raw);
$this->assertEquals('application/*', $res[1]->raw);
$accept = Accept::fromString('Accept: text/xml, application/xml');
$res = $accept->getPrioritized();
$this->assertEquals('application/xml', $res[0]->raw);
$this->assertEquals('text/xml', $res[1]->raw);
$accept = Accept::fromString('Accept: application/xml, text/xml');
$res = $accept->getPrioritized();
$this->assertEquals('application/xml', $res[0]->raw);
$this->assertEquals('text/xml', $res[1]->raw);
$accept = Accept::fromString('Accept: application/vnd.foobar+xml; q=0.9, text/xml');
$res = $accept->getPrioritized();
$this->assertEquals(1.0, $res[0]->getPriority());
$this->assertEquals(0.9, $res[1]->getPriority());
$this->assertEquals('application/vnd.foobar+xml', $res[1]->getTypeString());
$this->assertEquals('vnd.foobar+xml', $res[1]->getSubtypeRaw());
$this->assertEquals('vnd.foobar', $res[1]->getSubtype());
$this->assertEquals('xml', $res[1]->getFormat());
$accept = Accept::fromString('Accept: text/xml, application/vnd.foobar+xml; version="\'Ѿ"');
$res = $accept->getPrioritized();
$this->assertEquals('application/vnd.foobar+xml; version="\'Ѿ"', $res[0]->getRaw());
}
public function testWildcardDefaults()
{
$this->markTestIncomplete('No wildcard defaults implemented yet');
$expected = (object) [
'typeString' => 'image',
'type' => 'image',
'subtype' => '*',
'subtypeRaw' => '',
'format' => 'jpeg',
'priority' => 1,
'params' => [],
'raw' => 'image',
];
$this->assertEquals($expected, $acceptHdr->match('image'));
// $this->assertEquals($expected, $this->_handler->match('text'));
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Accept::fromString("Accept: application/text\r\n\r\nevilContent");
}
public function testGetEmptyFieldValue()
{
$accept = new Accept();
$accept->getFieldValue();
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AgeTest.php | test/Header/AgeTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Age;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class AgeTest extends TestCase
{
public function testAgeFromStringCreatesValidAgeHeader()
{
$ageHeader = Age::fromString('Age: 12');
$this->assertInstanceOf(HeaderInterface::class, $ageHeader);
$this->assertInstanceOf(Age::class, $ageHeader);
$this->assertEquals('12', $ageHeader->getDeltaSeconds());
}
public function testAgeGetFieldNameReturnsHeaderName()
{
$ageHeader = new Age();
$this->assertEquals('Age', $ageHeader->getFieldName());
}
public function testAgeGetFieldValueReturnsProperValue()
{
$ageHeader = new Age();
$ageHeader->setDeltaSeconds('12');
$this->assertEquals('12', $ageHeader->getFieldValue());
}
public function testAgeToStringReturnsHeaderFormattedString()
{
$ageHeader = new Age();
$ageHeader->setDeltaSeconds('12');
$this->assertEquals('Age: 12', $ageHeader->toString());
}
public function testAgeCorrectsDeltaSecondsOverflow()
{
$ageHeader = new Age();
$ageHeader->setDeltaSeconds(PHP_INT_MAX);
$this->assertEquals('Age: 2147483648', $ageHeader->toString());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
$header = Age::fromString("Age: 100\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
$header = new Age("100\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/IfModifiedSinceTest.php | test/Header/IfModifiedSinceTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\IfModifiedSince;
class IfModifiedSinceTest extends TestCase
{
public function testIfModifiedSinceFromStringCreatesValidIfModifiedSinceHeader()
{
$ifModifiedSinceHeader = IfModifiedSince::fromString('If-Modified-Since: Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertInstanceOf(HeaderInterface::class, $ifModifiedSinceHeader);
$this->assertInstanceOf(IfModifiedSince::class, $ifModifiedSinceHeader);
}
public function testIfModifiedSinceGetFieldNameReturnsHeaderName()
{
$ifModifiedSinceHeader = new IfModifiedSince();
$this->assertEquals('If-Modified-Since', $ifModifiedSinceHeader->getFieldName());
}
public function testIfModifiedSinceGetFieldValueReturnsProperValue()
{
$ifModifiedSinceHeader = new IfModifiedSince();
$ifModifiedSinceHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $ifModifiedSinceHeader->getFieldValue());
}
public function testIfModifiedSinceToStringReturnsHeaderFormattedString()
{
$ifModifiedSinceHeader = new IfModifiedSince();
$ifModifiedSinceHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('If-Modified-Since: Sun, 06 Nov 1994 08:49:37 GMT', $ifModifiedSinceHeader->toString());
}
/**
* Implementation specific tests are covered by DateTest
* @see ZendTest\Http\Header\DateTest
*/
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
IfModifiedSince::fromString(
"If-Modified-Since: Sun, 06 Nov 1994 08:49:37 GMT\r\n\r\nevilContent"
);
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/AuthenticationInfoTest.php | test/Header/AuthenticationInfoTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\AuthenticationInfo;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class AuthenticationInfoTest extends TestCase
{
public function testAuthenticationInfoFromStringCreatesValidAuthenticationInfoHeader()
{
$authenticationInfoHeader = AuthenticationInfo::fromString('Authentication-Info: xxx');
$this->assertInstanceOf(HeaderInterface::class, $authenticationInfoHeader);
$this->assertInstanceOf(AuthenticationInfo::class, $authenticationInfoHeader);
}
public function testAuthenticationInfoGetFieldNameReturnsHeaderName()
{
$authenticationInfoHeader = new AuthenticationInfo();
$this->assertEquals('Authentication-Info', $authenticationInfoHeader->getFieldName());
}
public function testAuthenticationInfoGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('AuthenticationInfo needs to be completed');
$authenticationInfoHeader = new AuthenticationInfo();
$this->assertEquals('xxx', $authenticationInfoHeader->getFieldValue());
}
public function testAuthenticationInfoToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('AuthenticationInfo needs to be completed');
$authenticationInfoHeader = new AuthenticationInfo();
// @todo set some values, then test output
$this->assertEmpty('Authentication-Info: xxx', $authenticationInfoHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
$header = AuthenticationInfo::fromString("Authentication-Info: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new AuthenticationInfo("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentSecurityPolicyTest.php | test/Header/ContentSecurityPolicyTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Exception\RuntimeException;
use Zend\Http\Header\ContentSecurityPolicy;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\GenericHeader;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\MultipleHeaderInterface;
use Zend\Http\Headers;
class ContentSecurityPolicyTest extends TestCase
{
public function testContentSecurityPolicyFromStringThrowsExceptionIfImproperHeaderNameUsed()
{
$this->expectException(InvalidArgumentException::class);
ContentSecurityPolicy::fromString('X-Content-Security-Policy: default-src *;');
}
public function testContentSecurityPolicyFromStringParsesDirectivesCorrectly()
{
$csp = ContentSecurityPolicy::fromString(
"Content-Security-Policy: default-src 'none'; script-src 'self'; img-src 'self'; style-src 'self';"
);
$this->assertInstanceOf(MultipleHeaderInterface::class, $csp);
$this->assertInstanceOf(HeaderInterface::class, $csp);
$this->assertInstanceOf(ContentSecurityPolicy::class, $csp);
$directives = [
'default-src' => "'none'",
'script-src' => "'self'",
'img-src' => "'self'",
'style-src' => "'self'",
];
$this->assertEquals($directives, $csp->getDirectives());
}
public function testContentSecurityPolicyGetFieldNameReturnsHeaderName()
{
$csp = new ContentSecurityPolicy();
$this->assertEquals('Content-Security-Policy', $csp->getFieldName());
}
public function testContentSecurityPolicyToStringReturnsHeaderFormattedString()
{
$csp = ContentSecurityPolicy::fromString(
"Content-Security-Policy: default-src 'none'; img-src 'self' https://*.gravatar.com;"
);
$this->assertInstanceOf(HeaderInterface::class, $csp);
$this->assertInstanceOf(ContentSecurityPolicy::class, $csp);
$this->assertEquals(
"Content-Security-Policy: default-src 'none'; img-src 'self' https://*.gravatar.com;",
$csp->toString()
);
}
public function testContentSecurityPolicySetDirective()
{
$csp = new ContentSecurityPolicy();
$csp->setDirective('default-src', ['https://*.google.com', 'http://foo.com'])
->setDirective('img-src', ["'self'"])
->setDirective('script-src', ['https://*.googleapis.com', 'https://*.bar.com']);
$header = 'Content-Security-Policy: default-src https://*.google.com http://foo.com; '
. 'img-src \'self\'; script-src https://*.googleapis.com https://*.bar.com;';
$this->assertEquals($header, $csp->toString());
}
public function testContentSecurityPolicySetDirectiveWithEmptySourcesDefaultsToNone()
{
$csp = new ContentSecurityPolicy();
$csp->setDirective('default-src', ["'self'"])
->setDirective('img-src', ['*'])
->setDirective('script-src', []);
$this->assertEquals(
"Content-Security-Policy: default-src 'self'; img-src *; script-src 'none';",
$csp->toString()
);
}
public function testContentSecurityPolicySetDirectiveThrowsExceptionIfInvalidDirectiveNameGiven()
{
$this->expectException(InvalidArgumentException::class);
$csp = new ContentSecurityPolicy();
$csp->setDirective('foo', []);
}
public function testContentSecurityPolicyGetFieldValueReturnsProperValue()
{
$csp = new ContentSecurityPolicy();
$csp->setDirective('default-src', ["'self'"])
->setDirective('img-src', ['https://*.github.com']);
$this->assertEquals("default-src 'self'; img-src https://*.github.com;", $csp->getFieldValue());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ContentSecurityPolicy::fromString("Content-Security-Policy: default-src 'none'\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaDirective()
{
$header = new ContentSecurityPolicy();
$this->expectException(InvalidArgumentException::class);
$header->setDirective('default-src', ["\rsome\r\nCRLF\ninjection"]);
}
public function testContentSecurityPolicySetDirectiveWithEmptyReportUriDefaultsToUnset()
{
$csp = new ContentSecurityPolicy();
$csp->setDirective('report-uri', []);
$this->assertEquals(
'Content-Security-Policy: ',
$csp->toString()
);
}
public function testContentSecurityPolicySetDirectiveWithEmptyReportUriRemovesExistingValue()
{
$csp = new ContentSecurityPolicy();
$csp->setDirective('report-uri', ['csp-error']);
$this->assertEquals(
'Content-Security-Policy: report-uri csp-error;',
$csp->toString()
);
$csp->setDirective('report-uri', []);
$this->assertEquals(
'Content-Security-Policy: ',
$csp->toString()
);
}
public function testToStringMultipleHeaders()
{
$csp = new ContentSecurityPolicy();
$csp->setDirective('default-src', ["'self'"]);
$additional = new ContentSecurityPolicy();
$additional->setDirective('img-src', ['https://*.github.com']);
self::assertSame(
"Content-Security-Policy: default-src 'self';\r\n"
. "Content-Security-Policy: img-src https://*.github.com;\r\n",
$csp->toStringMultipleHeaders([$additional])
);
}
public function testToStringMultipleHeadersExceptionIfDifferent()
{
$csp = new ContentSecurityPolicy();
$csp->setDirective('default-src', ["'self'"]);
$additional = new GenericHeader();
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage(
'The ContentSecurityPolicy multiple header implementation'
. ' can only accept an array of ContentSecurityPolicy headers'
);
$csp->toStringMultipleHeaders([$additional]);
}
public function testMultiple()
{
$headers = new Headers();
$headers->addHeader((new ContentSecurityPolicy())->setDirective('default-src', ["'self'"]));
$headers->addHeader((new ContentSecurityPolicy())->setDirective('img-src', ['https://*.github.com']));
self::assertSame(
"Content-Security-Policy: default-src 'self';\r\n"
. "Content-Security-Policy: img-src https://*.github.com;\r\n",
$headers->toString()
);
}
public static function validDirectives()
{
return [
['child-src', ["'self'"],"Content-Security-Policy: child-src 'self';"],
['manifest-src', ["'self'"], "Content-Security-Policy: manifest-src 'self';"],
['worker-src', ["'self'"], "Content-Security-Policy: worker-src 'self';"],
['prefetch-src', ["'self'"], "Content-Security-Policy: prefetch-src 'self';"],
['script-src-elem', ["'self'"], "Content-Security-Policy: script-src-elem 'self';"],
['script-src-attr', ["'self'"], "Content-Security-Policy: script-src-attr 'self';"],
['style-src-elem', ["'self'"], "Content-Security-Policy: style-src-elem 'self';"],
['style-src-attr', ["'self'"], "Content-Security-Policy: style-src-attr 'self';"],
['base-uri', ["'self'", "'unsafe-inline'"], "Content-Security-Policy: base-uri 'self' 'unsafe-inline';"],
['plugin-types', ['text/csv'], 'Content-Security-Policy: plugin-types text/csv;'],
[
'form-action',
['http://*.example.com', "'self'"],
"Content-Security-Policy: form-action http://*.example.com 'self';"
],
[
'frame-ancestors',
['http://*.example.com', "'self'"],
"Content-Security-Policy: frame-ancestors http://*.example.com 'self';"
],
['navigate-to', ['example.com'], 'Content-Security-Policy: navigate-to example.com;'],
['sandbox', ['allow-forms'], 'Content-Security-Policy: sandbox allow-forms;'],
// Other directives
['block-all-mixed-content', [], 'Content-Security-Policy: block-all-mixed-content;'],
['require-sri-for', ['script', 'style'], 'Content-Security-Policy: require-sri-for script style;'],
['trusted-types', ['*'], 'Content-Security-Policy: trusted-types *;'],
['upgrade-insecure-requests', [], 'Content-Security-Policy: upgrade-insecure-requests;'],
];
}
/**
* @dataProvider validDirectives
*
* @param string $directive
* @param string[] $values
* @param string $expected
*/
public function testContentSecurityPolicySetDirectiveThrowsExceptionIfMissingDirectiveNameGiven(
$directive,
array $values,
$expected
) {
$csp = new ContentSecurityPolicy();
$csp->setDirective($directive, $values);
self::assertSame($expected, $csp->toString());
}
/**
* @dataProvider validDirectives
*
* @param string $directive
* @param string[] $values
* @param string $header
*/
public function testFromString($directive, array $values, $header)
{
$contentSecurityPolicy = ContentSecurityPolicy::fromString($header);
self::assertArrayHasKey($directive, $contentSecurityPolicy->getDirectives());
self::assertSame(implode(' ', $values), $contentSecurityPolicy->getDirectives()[$directive]);
}
/**
* @return string
*/
public function directivesWithoutValue()
{
yield ['block-all-mixed-content'];
yield ['upgrade-insecure-requests'];
}
/**
* @dataProvider directivesWithoutValue
*
* @param string $directive
*/
public function testExceptionWhenProvideValueWithDirectiveWithoutValue($directive)
{
$csp = new ContentSecurityPolicy();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage($directive);
$csp->setDirective($directive, ['something']);
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentTypeTest.php | test/Header/ContentTypeTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\ContentType;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class ContentTypeTest extends TestCase
{
public function testContentTypeFromStringCreatesValidContentTypeHeader()
{
$contentTypeHeader = ContentType::fromString('Content-Type: xxx');
$this->assertInstanceOf(HeaderInterface::class, $contentTypeHeader);
$this->assertInstanceOf(ContentType::class, $contentTypeHeader);
}
public function testContentTypeGetFieldNameReturnsHeaderName()
{
$contentTypeHeader = new ContentType();
$this->assertEquals('Content-Type', $contentTypeHeader->getFieldName());
}
public function testContentTypeGetFieldValueReturnsProperValue()
{
$header = ContentType::fromString('Content-Type: application/json');
$this->assertEquals('application/json', $header->getFieldValue());
}
public function testContentTypeToStringReturnsHeaderFormattedString()
{
$header = new ContentType();
$header->setMediaType('application/atom+xml')
->setCharset('ISO-8859-1');
$this->assertEquals('Content-Type: application/atom+xml; charset=ISO-8859-1', $header->toString());
}
/** Implementation specific tests here */
public function wildcardMatches()
{
return [
'wildcard' => ['*/*'],
'wildcard-format' => ['*/*+*'],
'wildcard-type-subtype-fixed-format' => ['*/*+json'],
'wildcard-type-partial-wildcard-subtype-fixed-format' => ['*/vnd.*+json'],
'wildcard-type-format-subtype' => ['*/json'],
'fixed-type-wildcard-subtype' => ['application/*'],
'fixed-type-wildcard-subtype-fixed-format' => ['application/*+json'],
'fixed-type-format-subtype' => ['application/json'],
'fixed-type-fixed-subtype-wildcard-format' => ['application/vnd.foobar+*'],
'fixed-type-partial-wildcard-subtype-fixed-format' => ['application/vnd.*+json'],
'fixed' => ['application/vnd.foobar+json'],
'fixed-mixed-case' => ['APPLICATION/vnd.FooBar+json'],
];
}
/**
* @dataProvider wildcardMatches
*
* @param string $matchAgainst
*/
public function testMatchWildCard($matchAgainst)
{
$header = ContentType::fromString('Content-Type: application/vnd.foobar+json');
$result = $header->match($matchAgainst);
$this->assertEquals(strtolower($matchAgainst), $result);
}
public function invalidMatches()
{
return [
'format' => ['application/vnd.foobar+xml'],
'wildcard-subtype' => ['application/vendor.*+json'],
'subtype' => ['application/vendor.foobar+json'],
'type' => ['text/vnd.foobar+json'],
'wildcard-type-format' => ['*/vnd.foobar+xml'],
'wildcard-type-wildcard-subtype' => ['*/vendor.*+json'],
'wildcard-type-subtype' => ['*/vendor.foobar+json'],
];
}
/**
* @dataProvider invalidMatches
*
* @param string $matchAgainst
*/
public function testFailedMatches($matchAgainst)
{
$header = ContentType::fromString('Content-Type: application/vnd.foobar+json');
$result = $header->match($matchAgainst);
$this->assertFalse($result);
}
public function multipleCriteria()
{
$criteria = [
'application/vnd.foobar+xml',
'application/vnd.*+json',
'application/vendor.foobar+xml',
'*/vnd.foobar+json',
];
return [
'array' => [$criteria],
'string' => [implode(',', $criteria)],
];
}
/**
* @dataProvider multipleCriteria
*
* @param array|string $criteria
*/
public function testReturnsMatchingMediaTypeOfFirstCriteriaToValidate($criteria)
{
$header = ContentType::fromString('Content-Type: application/vnd.foobar+json');
$result = $header->match($criteria);
$this->assertEquals('application/vnd.*+json', $result);
}
public function contentTypeParameterExamples()
{
return [
'no-quotes' => ['Content-Type: foo/bar; param=baz', 'baz'],
'with-quotes' => ['Content-Type: foo/bar; param="baz"', 'baz'],
'with-equals' => ['Content-Type: foo/bar; param=baz=bat', 'baz=bat'],
'with-equals-and-quotes' => ['Content-Type: foo/bar; param="baz=bat"', 'baz=bat'],
];
}
/**
* @dataProvider contentTypeParameterExamples
*
* @param string $headerString
* @param string $expectedParameterValue
*/
public function testContentTypeParsesParametersCorrectly($headerString, $expectedParameterValue)
{
$contentTypeHeader = ContentType::fromString($headerString);
$parameters = $contentTypeHeader->getParameters();
$this->assertArrayHasKey('param', $parameters);
$this->assertSame($expectedParameterValue, $parameters['param']);
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ContentType::fromString("Content-Type: foo/bar;\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new ContentType("foo/bar\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/FromTest.php | test/Header/FromTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\From;
use Zend\Http\Header\HeaderInterface;
class FromTest extends TestCase
{
public function testFromFromStringCreatesValidFromHeader()
{
$fromHeader = From::fromString('From: xxx');
$this->assertInstanceOf(HeaderInterface::class, $fromHeader);
$this->assertInstanceOf(From::class, $fromHeader);
}
public function testFromGetFieldNameReturnsHeaderName()
{
$fromHeader = new From();
$this->assertEquals('From', $fromHeader->getFieldName());
}
public function testFromGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('From needs to be completed');
$fromHeader = new From();
$this->assertEquals('xxx', $fromHeader->getFieldValue());
}
public function testFromToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('From needs to be completed');
$fromHeader = new From();
// @todo set some values, then test output
$this->assertEmpty('From: xxx', $fromHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
From::fromString("From: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new From("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/IfRangeTest.php | test/Header/IfRangeTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\IfRange;
class IfRangeTest extends TestCase
{
public function testIfRangeFromStringCreatesValidIfRangeHeader()
{
$ifRangeHeader = IfRange::fromString('If-Range: xxx');
$this->assertInstanceOf(HeaderInterface::class, $ifRangeHeader);
$this->assertInstanceOf(IfRange::class, $ifRangeHeader);
}
public function testIfRangeGetFieldNameReturnsHeaderName()
{
$ifRangeHeader = new IfRange();
$this->assertEquals('If-Range', $ifRangeHeader->getFieldName());
}
public function testIfRangeGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('IfRange needs to be completed');
$ifRangeHeader = new IfRange();
$this->assertEquals('xxx', $ifRangeHeader->getFieldValue());
}
public function testIfRangeToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('IfRange needs to be completed');
$ifRangeHeader = new IfRange();
// @todo set some values, then test output
$this->assertEmpty('If-Range: xxx', $ifRangeHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
IfRange::fromString("If-Range: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new IfRange("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/CookieTest.php | test/Header/CookieTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use ArrayObject;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Cookie;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\SetCookie;
/**
* Zend_Http_Cookie unit tests
*
* @group Zend_Http
* @group Zend_Http_Cookie
*/
class CookieTest extends TestCase
{
public function testCookieFromStringCreatesValidCookieHeader()
{
$cookieHeader = Cookie::fromString('Cookie: name=value');
$this->assertInstanceOf(HeaderInterface::class, $cookieHeader);
$this->assertInstanceOf(ArrayObject::class, $cookieHeader);
$this->assertInstanceOf(Cookie::class, $cookieHeader);
}
public function testCookieFromStringCreatesValidCookieHeadersWithMultipleValues()
{
$cookieHeader = Cookie::fromString('Cookie: name=value; foo=bar');
$this->assertEquals('value', $cookieHeader->name);
$this->assertEquals('bar', $cookieHeader['foo']);
}
public function testCookieFromSetCookieArrayProducesASingleCookie()
{
$setCookies = [
new SetCookie('foo', 'bar'),
new SetCookie('name', 'value'),
];
$cookie = Cookie::fromSetCookieArray($setCookies);
$this->assertEquals('Cookie: foo=bar; name=value', $cookie->toString());
}
public function testCookieGetFieldNameReturnsHeaderName()
{
$cookieHeader = new Cookie();
$this->assertEquals('Cookie', $cookieHeader->getFieldName());
}
public function testCookieGetFieldValueReturnsProperValue()
{
$cookieHeader = new Cookie();
$cookieHeader->foo = 'bar';
$this->assertEquals('foo=bar', $cookieHeader->getFieldValue());
}
public function testCookieToStringReturnsHeaderFormattedString()
{
$cookieHeader = new Cookie();
$cookieHeader->foo = 'bar';
$this->assertEquals('Cookie: foo=bar', $cookieHeader->toString());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Cookie::fromString("Cookie: foo=bar\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*
* @dataProvider valuesProvider
*
* @param mixed $value
* @param string $serialized
*/
public function testSerialization($value, $serialized)
{
$header = new Cookie([$value]);
$this->assertEquals('Cookie: ' . $serialized, $header->toString());
}
public function valuesProvider()
{
return [
// Description => [raw value, serialized]
'CRLF characters' => ["foo=bar\r\n\r\nevilContent", '0=foo%3Dbar%0D%0A%0D%0AevilContent'],
];
}
// @codingStandardsIgnoreStart
// /**
// * Cookie creation and data accessors tests
// */
//
// /**
// * Make sure we can't set invalid names
// *
// * @dataProvider invalidCookieNameCharProvider
// *
// * @param string $char
// */
// public function testSetInvalidName($char)
// {
// $this->expectException(InvalidArgumentException::class);
// $this->expectExceptionMessage('Cookie name cannot contain these characters');
//
// $cookie = new Http\Cookie("cookie_$char", 'foo', 'example.com');
// }
//
// /**
// * Test we get the cookie name properly
// *
// * @dataProvider validCookieWithInfoProvider
// *
// * @param string $cStr
// * @param array $cInfo
// */
// public function testGetName($cStr, array $cInfo)
// {
// $cookie = Http\Cookie::fromString($cStr);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object from '$cStr'");
// }
//
// if (isset($cInfo['name'])) {
// $this->assertEquals($cInfo['name'], $cookie->getName());
// }
// }
//
// /**
// * Make sure we get the correct value if it was set through the constructor
// *
// * @dataProvider validCookieValueProvider
// *
// * @param string $value
// */
// public function testGetValueConstructor($val)
// {
// $cookie = new Http\Cookie('cookie', $val, 'example.com', time(), '/', true);
// $this->assertEquals($val, $cookie->getValue());
// }
//
// /**
// * Make sure we get the correct value if it was set through fromString()
// *
// * @dataProvider validCookieValueProvider
// *
// * @param string $value
// */
// public function testGetValueFromString($val)
// {
// $cookie = Http\Cookie::fromString('cookie=' . urlencode($val) . '; domain=example.com');
// $this->assertEquals($val, $cookie->getValue());
// }
//
// /**
// * Make sure we get the correct value if it was set through fromString()
// *
// * @dataProvider validCookieValueProvider
// *
// * @param string $value
// */
// public function testGetRawValueFromString($val)
// {
// // Because ';' has special meaning in the cookie, strip it out for this test.
// $val = str_replace(';', '', $val);
// $cookie = Http\Cookie::fromString('cookie=' . $val . '; domain=example.com', null, false);
// $this->assertEquals($val, $cookie->getValue());
// }
//
// /**
// * Make sure we get the correct value if it was set through fromString()
// *
// * @dataProvider validCookieValueProvider
// *
// * @param string $value
// */
// public function testGetRawValueFromStringToString($val)
// {
// // Because ';' has special meaning in the cookie, strip it out for this test.
// $val = str_replace(';', '', $val);
// $cookie = Http\Cookie::fromString('cookie=' . $val . '; domain=example.com', null, false);
// $this->assertEquals('cookie=' . $val . ';', (string) $cookie);
// }
//
// /**
// * Make sure we get the correct value if it was set through fromString()
// *
// * @dataProvider validCookieValueProvider
// *
// * @param string $value
// */
// public function testGetValueFromStringEncodedToString($val)
// {
// // Because ';' has special meaning in the cookie, strip it out for this test.
// $val = str_replace(';', '', $val);
// $cookie = Http\Cookie::fromString('cookie=' . $val . '; domain=example.com', null, true);
// $this->assertEquals('cookie=' . urlencode($val) . ';', (string) $cookie);
// }
//
// /**
// * Make sure we get the correct domain when it's set in the cookie string
// *
// * @dataProvider validCookieWithInfoProvider
// *
// * @param string $cStr
// * @param array $cInfo
// */
// public function testGetDomainInStr($cStr, array $cInfo)
// {
// $cookie = Http\Cookie::fromString($cStr);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object from '$cStr'");
// }
//
// if (isset($cInfo['domain'])) {
// $this->assertEquals($cInfo['domain'], $cookie->getDomain());
// }
// }
//
// /**
// * Make sure we get the correct domain when it's set in a reference URL
// *
// * @dataProvider refUrlProvider
// *
// * @param Uri\Uri $uri
// */
// public function testGetDomainInRefUrl(Uri\Uri $uri)
// {
// $domain = $uri->getHost();
// $cookie = Http\Cookie::fromString('foo=baz; path=/', 'http://' . $domain);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object with URL '$uri'");
// }
//
// $this->assertEquals($domain, $cookie->getDomain());
// }
//
// /**
// * Make sure we get the correct path when it's set in the cookie string
// *
// * @dataProvider validCookieWithInfoProvider
// *
// * @param string $cStr
// * @param array $cInfo
// */
// public function testGetPathInStr($cStr, array $cInfo)
// {
// $cookie = Http\Cookie::fromString($cStr);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object from '$cStr'");
// }
//
// if (isset($cInfo['path'])) {
// $this->assertEquals($cInfo['path'], $cookie->getPath());
// }
// }
//
// /**
// * Make sure we get the correct path when it's set a reference URL
// *
// * @dataProvider refUrlProvider
// *
// * @param Uri\Uri $uri
// */
// public function testGetPathInRefUrl(Uri\Uri $uri)
// {
// $path = $uri->getPath();
// if (substr($path, -1, 1) == '/') $path .= 'x';
// $path = dirname($path);
// if (($path == DIRECTORY_SEPARATOR) || empty($path)) {
// $path = '/';
// }
//
// $cookie = Http\Cookie::fromString('foo=bar', (string) $uri);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object with URL '$uri'");
// }
//
// $this->assertEquals($path, $cookie->getPath());
// }
//
// /**
// * Test we get the correct expiry time
// *
// * @dataProvider validCookieWithInfoProvider
// *
// * @param string $cStr
// * @param array $cInfo
// */
// public function testGetExpiryTime($cStr, array $cInfo)
// {
// $cookie = Http\Cookie::fromString($cStr);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object from '$cStr'");
// }
//
// if (isset($cInfo['expires'])) {
// $this->assertEquals($cInfo['expires'], $cookie->getExpiryTime());
// }
// }
//
// /**
// * Make sure the "is secure" flag is correctly set
// *
// * @dataProvider validCookieWithInfoProvider
// *
// * @param string $cStr
// * @param array $cInfo
// */
// public function testIsSecure($cStr, array $cInfo)
// {
// $cookie = Http\Cookie::fromString($cStr);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object from '$cStr'");
// }
//
// if (isset($cInfo['secure'])) {
// $this->assertEquals($cInfo['secure'], $cookie->isSecure());
// }
// }
//
// /**
// * Cookie expiry time tests
// */
//
// /**
// * Make sure we get the correct value for 'isExpired'
// *
// * @dataProvider cookieWithExpiredFlagProvider
// *
// * @param string $cStr
// * @param bool $expired
// */
// public function testIsExpired($cStr, $expired)
// {
// $cookie = Http\Cookie::fromString($cStr);
// if (! $cookie) {
// $this->fail("Failed creating a cookie object from '$cStr'");
// }
// $this->assertEquals($expired, $cookie->isExpired());
// }
//
// /**
// * Make sure we get the correct value for 'isExpired', when time is manually set
// */
// public function testIsExpiredDifferentTime()
// {
// $notexpired = time() + 3600;
// $expired = time() - 3600;
// $now = time() + 7200;
//
// $cookies = [
// 'cookie=foo; domain=example.com; expires=' . date(DATE_COOKIE, $notexpired),
// 'cookie=foo; domain=example.com; expires=' . date(DATE_COOKIE, $expired),
// ];
//
// // Make sure all cookies are expired
// foreach ($cookies as $cstr) {
// $cookie = Http\Cookie::fromString($cstr);
// if (! $cookie) $this->fail('Got no cookie object from a valid cookie string');
// $this->assertTrue($cookie->isExpired($now), 'Cookie is expected to be expired');
// }
//
// // Make sure all cookies are not expired
// $now = time() - 7200;
// foreach ($cookies as $cstr) {
// $cookie = Http\Cookie::fromString($cstr);
// if (! $cookie) $this->fail('Got no cookie object from a valid cookie string');
// $this->assertFalse($cookie->isExpired($now), 'Cookie is expected not to be expired');
// }
// }
//
// /**
// * Test we can properly check if a cookie is a session cookie (has no expiry time)
// *
// * @dataProvider validCookieWithInfoProvider
// *
// * @param string $cStr
// * @param array $cInfo
// */
// public function testIsSessionCookie($cStr, array $cInfo)
// {
// $cookie = Http\Cookie::fromString($cStr);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object from '$cStr'");
// }
//
// if (array_key_exists('expires', $cInfo)) {
// $this->assertEquals(($cInfo['expires'] === null), $cookie->isSessionCookie());
// }
// }
//
//
// /**
// * Make sure cookies are properly converted back to strings
// *
// * @dataProvider validCookieWithInfoProvider
// *
// * @param string $cStr
// * @param array $cInfo
// */
// public function testToString($cStr, array $cInfo)
// {
// $cookie = Http\Cookie::fromString($cStr);
// if (! $cookie instanceof Http\Cookie) {
// $this->fail("Failed creating a cookie object from '$cStr'");
// }
//
// $expected = substr($cStr, 0, strpos($cStr, ';') + 1);
// $this->assertEquals($expected, (string) $cookie);
// }
//
// public function testGarbageInStrIsIgnored()
// {
// $cookies = [
// 'name=value; domain=foo.com; silly=place; secure',
// 'foo=value; someCrap; secure; domain=foo.com; ',
// 'anothercookie=value; secure; has some crap; ignore=me; domain=foo.com; ',
// ];
//
// foreach ($cookies as $cstr) {
// $cookie = Http\Cookie::fromString($cstr);
// if (! $cookie) $this->fail('Got no cookie object from a valid cookie string');
// $this->assertEquals('value', $cookie->getValue(), 'Value is not as expected');
// $this->assertEquals('foo.com', $cookie->getDomain(), 'Domain is not as expected');
// $this->assertTrue($cookie->isSecure(), 'Cookie is expected to be secure');
// }
// }
//
// /**
// * Test the match() method against a domain
// *
// * @dataProvider domainMatchTestProvider
// *
// * @param string $cookieStr
// * @param Uri\Uri|string $uri
// * @param bool $match
// */
// public function testMatchDomain($cookieStr, $uri, $match)
// {
// $cookie = Http\Cookie::fromString($cookieStr);
// $this->assertEquals($match, $cookie->match($uri));
// }
//
// static public function domainMatchTestProvider()
// {
// $uri = new Uri\Uri('http://www.foo.com/some/file.txt');
//
// return [
// ['foo=bar; domain=.example.com;', 'http://www.example.com/foo/bar.php', true],
// ['foo=bar; domain=.example.com;', 'http://example.com/foo/bar.php', true],
// ['foo=bar; domain=.example.com;', 'http://www.somexample.com/foo/bar.php', false],
// ['foo=bar; domain=example.com;', 'http://www.somexample.com/foo/bar.php', false],
// ['cookie=value; domain=www.foo.com', $uri, true],
// ['cookie=value; domain=www.foo.com', 'http://il.www.foo.com', true],
// ['cookie=value; domain=www.foo.com', 'http://bar.foo.com', false],
// ];
// }
//
// /**
// * Test the match() method against a domain
// *
// */
// public function testMatchPath()
// {
// $cookie = Http\Cookie::fromString('foo=bar; domain=.example.com; path=/foo');
// $this->assertTrue($cookie->match('http://www.example.com/foo/bar.php'), 'Cookie expected to match, but didn\'t');
// $this->assertFalse($cookie->match('http://www.example.com/bar.php'), 'Cookie expected not to match, but did');
//
// $cookie = Http\Cookie::fromString('cookie=value; domain=www.foo.com; path=/some/long/path');
// $this->assertTrue($cookie->match('http://www.foo.com/some/long/path/file.txt'), 'Cookie expected to match, but didn\'t');
// $this->assertTrue($cookie->match('http://www.foo.com/some/long/path/and/even/more'), 'Cookie expected to match, but didn\'t');
// $this->assertFalse($cookie->match('http://www.foo.com/some/long/file.txt'), 'Cookie expected not to match, but did');
// $this->assertFalse($cookie->match('http://www.foo.com/some/different/path/file.txt'), 'Cookie expected not to match, but did');
// }
//
// /**
// * Test the match() method against secure / non secure connections
// *
// */
// public function testMatchSecure()
// {
// // A non secure cookie, should match both
// $cookie = Http\Cookie::fromString('foo=bar; domain=.example.com;');
// $this->assertTrue($cookie->match('http://www.example.com/foo/bar.php'), 'Cookie expected to match, but didn\'t');
// $this->assertTrue($cookie->match('https://www.example.com/bar.php'), 'Cookie expected to match, but didn\'t');
//
// // A secure cookie, should match secure connections only
// $cookie = Http\Cookie::fromString('foo=bar; domain=.example.com; secure');
// $this->assertFalse($cookie->match('http://www.example.com/foo/bar.php'), 'Cookie expected not to match, but it did');
// $this->assertTrue($cookie->match('https://www.example.com/bar.php'), 'Cookie expected to match, but didn\'t');
// }
//
// /**
// * Test the match() method against different expiry times
// *
// */
// public function testMatchExpire()
// {
// // A session cookie - should always be valid
// $cookie = Http\Cookie::fromString('foo=bar; domain=.example.com;');
// $this->assertTrue($cookie->match('http://www.example.com/'), 'Cookie expected to match, but didn\'t');
// $this->assertTrue($cookie->match('http://www.example.com/', true, time() + 3600), 'Cookie expected to match, but didn\'t');
//
// // A session cookie, should not match
// $this->assertFalse($cookie->match('https://www.example.com/', false), 'Cookie expected not to match, but it did');
// $this->assertFalse($cookie->match('https://www.example.com/', false, time() - 3600), 'Cookie expected not to match, but it did');
//
// // A cookie with expiry time in the future
// $cookie = Http\Cookie::fromString('foo=bar; domain=.example.com; expires=' . date(DATE_COOKIE, time() + 3600));
// $this->assertTrue($cookie->match('http://www.example.com/'), 'Cookie expected to match, but didn\'t');
// $this->assertFalse($cookie->match('https://www.example.com/', true, time() + 7200), 'Cookie expected not to match, but it did');
//
// // A cookie with expiry time in the past
// $cookie = Http\Cookie::fromString('foo=bar; domain=.example.com; expires=' . date(DATE_COOKIE, time() - 3600));
// $this->assertFalse($cookie->match('http://www.example.com/'), 'Cookie expected not to match, but it did');
// $this->assertTrue($cookie->match('https://www.example.com/', true, time() - 7200), 'Cookie expected to match, but didn\'t');
// }
//
// public function testFromStringFalse()
// {
// $cookie = Http\Cookie::fromString('foo; domain=www.exmaple.com');
// $this->assertEquals(false, $cookie, 'fromString was expected to fail and return false');
//
// $cookie = Http\Cookie::fromString('=bar; secure; domain=foo.nl');
// $this->assertEquals(false, $cookie, 'fromString was expected to fail and return false');
//
// $cookie = Http\Cookie::fromString('fo;o=bar; secure; domain=foo.nl');
// $this->assertEquals(false, $cookie, 'fromString was expected to fail and return false');
// }
//
// /**
// * Test that cookies with far future expiry date (beyond the 32 bit unsigned int range) are
// * not mistakenly marked as 'expired'
// *
// * @todo re-enable once Locale is working
// * @group disable
// * @link http://framework.zend.com/issues/browse/ZF-5690
// */
// public function testZF5690OverflowingExpiryDate()
// {
// $expTime = "Sat, 29-Jan-2039 00:54:42 GMT";
// $cookie = Http\Cookie::fromString("foo=bar; domain=.example.com; expires=$expTime");
// $this->assertFalse($cookie->isExpired(), 'Expiry: ' . $cookie->getExpiryTime());
// }
//
// /**
// * Data Providers
// */
//
// /**
// * Provide characters which are invalid in cookie names
// *
// * @return array
// */
// static public function invalidCookieNameCharProvider()
// {
// return [
// ["="],
// [","],
// [";"],
// ["\t"],
// ["\r"],
// ["\n"],
// ["\013"],
// ["\014"],
// ];
// }
//
// /**
// * Provide valid cookie values
// *
// * @return array
// */
// static public function validCookieValueProvider()
// {
// return [
// ['simpleCookie'],
// ['space cookie'],
// ['!@#$%^*&()* ][{}?;'],
// ["line\n\rbreaks"],
// ["0000j8CydACPu_-J9bE8uTX91YU:12a83ks4k"], // value from: Alexander Cheshchevik's comment on issue: ZF-1850
//
// // Long cookie value - 2kb
// [str_repeat(md5(time()), 64)],
// ];
// }
//
// /**
// * Provider of valid reference URLs to be used for creating cookies
// *
// * @return array
// */
// static public function refUrlProvider()
// {
// return [
// [new Uri\Uri('http://example.com/')],
// [new Uri\Uri('http://www.example.com/foo/bar/')],
// [new Uri\Uri('http://some.really.deep.domain.com')],
// [new Uri\Uri('http://localhost/path/to/very/deep/file.php')],
// [new Uri\Uri('http://arr.gr/some%20path/text%2Ffile')],
// ];
// }
//
// /**
// * Provide valid cookie strings with information about them
// *
// * @return array
// */
// static public function validCookieWithInfoProvider()
// {
// $now = time();
// $yesterday = $now - (3600 * 24);
//
// return [
// [
// 'justacookie=foo; domain=example.com',
// [
// 'name' => 'justacookie',
// 'domain' => 'example.com',
// 'path' => '/',
// 'expires' => null,
// 'secure' => false,
// ],
// ],
// [
// 'expires=tomorrow; secure; path=/Space Out/; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=.example.com',
// [
// 'name' => 'expires',
// 'domain' => '.example.com',
// 'path' => '/Space Out/',
// 'expires' => strtotime('Tue, 21-Nov-2006 08:33:44 GMT'),
// 'secure' => true,
// ],
// ],
// [
// 'domain=unittests; expires=' . date(DATE_COOKIE, $now) . '; domain=example.com; path=/some%20value/',
// [
// 'name' => 'domain',
// 'domain' => 'example.com',
// 'path' => '/some%20value/',
// 'expires' => $now,
// 'secure' => false,
// ],
// ],
// [
// 'path=indexAction; path=/; domain=.foo.com; expires=' . date(DATE_COOKIE, $yesterday),
// [
// 'name' => 'path',
// 'domain' => '.foo.com',
// 'path' => '/',
// 'expires' => $yesterday,
// 'secure' => false,
// ],
// ],
// [
// 'secure=sha1; secure; SECURE; domain=some.really.deep.domain.com',
// [
// 'name' => 'secure',
// 'domain' => 'some.really.deep.domain.com',
// 'path' => '/',
// 'expires' => null,
// 'secure' => true,
// ],
// ],
// [
// 'PHPSESSID=123456789+abcd%2Cef; secure; domain=.localdomain; path=/foo/baz; expires=Tue, 21-Nov-2006 08:33:44 GMT;',
// [
// 'name' => 'PHPSESSID',
// 'domain' => '.localdomain',
// 'path' => '/foo/baz',
// 'expires' => strtotime('Tue, 21-Nov-2006 08:33:44 GMT'),
// 'secure' => true,
// ],
// ],
// ];
// }
//
// /**
// * Cookie with 'expired' flag, used to test if Cookie->isExpired()
// *
// * @todo re-enable commented cookie arguments once Locale is working
// * @return array
// */
// public static function cookieWithExpiredFlagProvider()
// {
// return [
// ['cookie=foo;domain=example.com;expires=' . date(DATE_COOKIE, time() + 12 * 3600), false],
// ['cookie=foo;domain=example.com;expires=' . date(DATE_COOKIE, time() - 15), true],
// ['cookie=foo;domain=example.com;', false],
// // ['cookie=foo;domain=example.com;expires=Fri, 01-Mar-2109 00:19:21 GMT', false],
// // ['cookie=foo;domain=example.com;expires=Fri, 06-Jun-1966 00:19:21 GMT', true],
// ];
// }
// @codingStandardsIgnoreEnd
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/SetCookieTest.php | test/Header/SetCookieTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use DateTime;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\MultipleHeaderInterface;
use Zend\Http\Header\SetCookie;
use function strtolower;
use function strtoupper;
class SetCookieTest extends TestCase
{
/**
* @group ZF2-254
*/
public function testSetCookieConstructor()
{
$setCookieHeader = new SetCookie(
'myname',
'myvalue',
'Wed, 13-Jan-2021 22:23:01 GMT',
'/accounts',
'docs.foo.com',
true,
true,
99,
9
);
$this->assertEquals('myname', $setCookieHeader->getName());
$this->assertEquals('myvalue', $setCookieHeader->getValue());
$this->assertEquals('Wed, 13-Jan-2021 22:23:01 GMT', $setCookieHeader->getExpires());
$this->assertEquals('/accounts', $setCookieHeader->getPath());
$this->assertEquals('docs.foo.com', $setCookieHeader->getDomain());
$this->assertTrue($setCookieHeader->isSecure());
$this->assertTrue($setCookieHeader->isHttpOnly());
$this->assertEquals(99, $setCookieHeader->getMaxAge());
$this->assertEquals(9, $setCookieHeader->getVersion());
}
public function testSetCookieConstructorWithSameSite()
{
$setCookieHeader = new SetCookie(
'myname',
'myvalue',
'Wed, 13-Jan-2021 22:23:01 GMT',
'/accounts',
'docs.foo.com',
true,
true,
99,
9,
SetCookie::SAME_SITE_STRICT
);
$this->assertEquals('myname', $setCookieHeader->getName());
$this->assertEquals('myvalue', $setCookieHeader->getValue());
$this->assertEquals('Wed, 13-Jan-2021 22:23:01 GMT', $setCookieHeader->getExpires());
$this->assertEquals('/accounts', $setCookieHeader->getPath());
$this->assertEquals('docs.foo.com', $setCookieHeader->getDomain());
$this->assertTrue($setCookieHeader->isSecure());
$this->assertTrue($setCookieHeader->isHttpOnly());
$this->assertEquals(99, $setCookieHeader->getMaxAge());
$this->assertEquals(9, $setCookieHeader->getVersion());
$this->assertEquals('Strict', $setCookieHeader->getSameSite());
}
public function testSetCookieConstructorWithSameSiteCaseInsensitive()
{
$setCookieHeader = new SetCookie(
'myname',
'myvalue',
'Wed, 13-Jan-2021 22:23:01 GMT',
'/accounts',
'docs.foo.com',
true,
true,
99,
9,
strtolower(SetCookie::SAME_SITE_STRICT)
);
$this->assertEquals('myname', $setCookieHeader->getName());
$this->assertEquals('myvalue', $setCookieHeader->getValue());
$this->assertEquals('Wed, 13-Jan-2021 22:23:01 GMT', $setCookieHeader->getExpires());
$this->assertEquals('/accounts', $setCookieHeader->getPath());
$this->assertEquals('docs.foo.com', $setCookieHeader->getDomain());
$this->assertTrue($setCookieHeader->isSecure());
$this->assertTrue($setCookieHeader->isHttpOnly());
$this->assertEquals(99, $setCookieHeader->getMaxAge());
$this->assertEquals(9, $setCookieHeader->getVersion());
$this->assertEquals(SetCookie::SAME_SITE_STRICT, $setCookieHeader->getSameSite());
}
public function testSetCookieWithInvalidSameSiteValueThrowException()
{
$this->expectException(InvalidArgumentException::class);
new SetCookie(
'myname',
'myvalue',
'Wed, 13-Jan-2021 22:23:01 GMT',
'/accounts',
'docs.foo.com',
true,
true,
99,
9,
'InvalidValue'
);
}
public function testSetInvalidSameSiteDirectiveValueViaSetter()
{
$setCookieHeader = new SetCookie(
'myname',
'myvalue',
'Wed, 13-Jan-2021 22:23:01 GMT',
'/accounts',
'docs.foo.com',
true,
true,
99,
9
);
$this->expectException(InvalidArgumentException::class);
$setCookieHeader->setSameSite('InvalidValue');
}
public function testSameSiteGetterReturnsCanonicalValue()
{
$setCookieHeader = new SetCookie(
'myname',
'myvalue',
'Wed, 13-Jan-2021 22:23:01 GMT',
'/accounts',
'docs.foo.com',
true,
true,
99,
9,
SetCookie::SAME_SITE_STRICT
);
$this->assertEquals(SetCookie::SAME_SITE_STRICT, $setCookieHeader->getSameSite());
$setCookieHeader->setSameSite(strtolower(SetCookie::SAME_SITE_LAX));
$this->assertEquals(SetCookie::SAME_SITE_LAX, $setCookieHeader->getSameSite());
$setCookieHeader->setSameSite(strtoupper(SetCookie::SAME_SITE_NONE));
$this->assertEquals(SetCookie::SAME_SITE_NONE, $setCookieHeader->getSameSite());
}
public function testSetCookieFromStringWithQuotedValue()
{
$setCookieHeader = SetCookie::fromString('Set-Cookie: myname="quotedValue"');
$this->assertEquals('quotedValue', $setCookieHeader->getValue());
$this->assertEquals('myname=quotedValue', $setCookieHeader->getFieldValue());
}
public function testSetCookieFromStringWithNotEncodedValue()
{
$setCookieHeader = SetCookie::fromString('Set-Cookie: foo=a:b; Path=/');
$this->assertFalse($setCookieHeader->getEncodeValue());
$this->assertEquals('a:b', $setCookieHeader->getValue());
$this->assertEquals('foo=a:b; Path=/', $setCookieHeader->getFieldValue());
}
public function testSetCookieFromStringCreatesValidSetCookieHeader()
{
$setCookieHeader = SetCookie::fromString('Set-Cookie: xxx');
$this->assertInstanceOf(MultipleHeaderInterface::class, $setCookieHeader);
$this->assertInstanceOf(HeaderInterface::class, $setCookieHeader);
$this->assertInstanceOf(SetCookie::class, $setCookieHeader);
}
public function testSetCookieFromStringCanCreateSingleHeader()
{
$setCookieHeader = SetCookie::fromString('Set-Cookie: myname=myvalue');
$this->assertInstanceOf(HeaderInterface::class, $setCookieHeader);
$this->assertEquals('myname', $setCookieHeader->getName());
$this->assertEquals('myvalue', $setCookieHeader->getValue());
$setCookieHeader = SetCookie::fromString(
'set-cookie: myname=myvalue; Domain=docs.foo.com; Path=/accounts;'
. 'Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly'
);
$this->assertInstanceOf(MultipleHeaderInterface::class, $setCookieHeader);
$this->assertEquals('myname', $setCookieHeader->getName());
$this->assertEquals('myvalue', $setCookieHeader->getValue());
$this->assertEquals('docs.foo.com', $setCookieHeader->getDomain());
$this->assertEquals('/accounts', $setCookieHeader->getPath());
$this->assertEquals('Wed, 13-Jan-2021 22:23:01 GMT', $setCookieHeader->getExpires());
$this->assertTrue($setCookieHeader->isSecure());
$this->assertTrue($setCookieHeader->isHttponly());
$setCookieHeader = SetCookie::fromString(
'set-cookie: myname=myvalue; Domain=docs.foo.com; Path=/accounts;'
. 'Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly; SameSite=Strict'
);
$this->assertInstanceOf(MultipleHeaderInterface::class, $setCookieHeader);
$this->assertEquals('myname', $setCookieHeader->getName());
$this->assertEquals('myvalue', $setCookieHeader->getValue());
$this->assertEquals('docs.foo.com', $setCookieHeader->getDomain());
$this->assertEquals('/accounts', $setCookieHeader->getPath());
$this->assertEquals('Wed, 13-Jan-2021 22:23:01 GMT', $setCookieHeader->getExpires());
$this->assertTrue($setCookieHeader->isSecure());
$this->assertTrue($setCookieHeader->isHttponly());
$this->assertEquals(setCookie::SAME_SITE_STRICT, $setCookieHeader->getSameSite());
$setCookieHeader = SetCookie::fromString(
'set-cookie: myname=myvalue; Domain=docs.foo.com; Path=/accounts;'
. 'Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly; SameSite=strict'
);
$this->assertInstanceOf(MultipleHeaderInterface::class, $setCookieHeader);
$this->assertEquals('myname', $setCookieHeader->getName());
$this->assertEquals('myvalue', $setCookieHeader->getValue());
$this->assertEquals('docs.foo.com', $setCookieHeader->getDomain());
$this->assertEquals('/accounts', $setCookieHeader->getPath());
$this->assertEquals('Wed, 13-Jan-2021 22:23:01 GMT', $setCookieHeader->getExpires());
$this->assertTrue($setCookieHeader->isSecure());
$this->assertTrue($setCookieHeader->isHttponly());
$this->assertEquals(setCookie::SAME_SITE_STRICT, $setCookieHeader->getSameSite());
}
public function testFieldValueWithSameSiteCaseInsensitive()
{
$setCookieHeader = SetCookie::fromString(
'set-cookie: myname=myvalue; SameSite=Strict'
);
$this->assertEquals(
'myname=myvalue; SameSite=Strict',
$setCookieHeader->getFieldValue()
);
$setCookieHeader = SetCookie::fromString(
'set-cookie: myname=myvalue; SameSite=strict'
);
$this->assertEquals(
'myname=myvalue; SameSite=Strict',
$setCookieHeader->getFieldValue()
);
}
public function testSetCookieFromStringCanCreateMultipleHeaders()
{
$setCookieHeaders = SetCookie::fromString(
'Set-Cookie: myname=myvalue, '
. 'someothername=someothervalue; Domain=docs.foo.com; Path=/accounts;'
. 'Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly'
);
$this->assertInternalType('array', $setCookieHeaders);
$setCookieHeader = $setCookieHeaders[0];
$this->assertInstanceOf(MultipleHeaderInterface::class, $setCookieHeader);
$this->assertEquals('myname', $setCookieHeader->getName());
$this->assertEquals('myvalue', $setCookieHeader->getValue());
$setCookieHeader = $setCookieHeaders[1];
$this->assertInstanceOf(MultipleHeaderInterface::class, $setCookieHeader);
$this->assertEquals('someothername', $setCookieHeader->getName());
$this->assertEquals('someothervalue', $setCookieHeader->getValue());
$this->assertEquals('Wed, 13-Jan-2021 22:23:01 GMT', $setCookieHeader->getExpires());
$this->assertEquals('docs.foo.com', $setCookieHeader->getDomain());
$this->assertEquals('/accounts', $setCookieHeader->getPath());
$this->assertTrue($setCookieHeader->isSecure());
$this->assertTrue($setCookieHeader->isHttponly());
}
public function testSetCookieGetFieldNameReturnsHeaderName()
{
$setCookieHeader = new SetCookie();
$this->assertEquals('Set-Cookie', $setCookieHeader->getFieldName());
}
public function testSetCookieGetFieldValueReturnsProperValue()
{
$setCookieHeader = new SetCookie();
$setCookieHeader->setName('myname');
$setCookieHeader->setValue('myvalue');
$setCookieHeader->setExpires('Wed, 13-Jan-2021 22:23:01 GMT');
$setCookieHeader->setDomain('docs.foo.com');
$setCookieHeader->setPath('/accounts');
$setCookieHeader->setSecure(true);
$setCookieHeader->setHttponly(true);
$target = 'myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT;'
. ' Domain=docs.foo.com; Path=/accounts;'
. ' Secure; HttpOnly';
$this->assertEquals($target, $setCookieHeader->getFieldValue());
}
/**
* @group 6673
* @group 6923
*/
public function testSetCookieWithDateTimeFieldValueReturnsProperValue()
{
$setCookieHeader = new SetCookie();
$setCookieHeader->setName('myname');
$setCookieHeader->setValue('myvalue');
$setCookieHeader->setExpires(new DateTime('Wed, 13-Jan-2021 22:23:01 GMT'));
$setCookieHeader->setDomain('docs.foo.com');
$setCookieHeader->setPath('/accounts');
$setCookieHeader->setSecure(true);
$setCookieHeader->setHttponly(true);
$target = 'myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT;'
. ' Domain=docs.foo.com; Path=/accounts;'
. ' Secure; HttpOnly';
$this->assertEquals($target, $setCookieHeader->getFieldValue());
}
public function testSetCookieToStringReturnsHeaderFormattedString()
{
$setCookieHeader = new SetCookie();
$setCookieHeader->setName('myname');
$setCookieHeader->setValue('myvalue');
$setCookieHeader->setExpires('Wed, 13-Jan-2021 22:23:01 GMT');
$setCookieHeader->setDomain('docs.foo.com');
$setCookieHeader->setPath('/accounts');
$setCookieHeader->setSecure(true);
$setCookieHeader->setHttponly(true);
$target = 'Set-Cookie: myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT;'
. ' Domain=docs.foo.com; Path=/accounts;'
. ' Secure; HttpOnly';
$this->assertEquals($target, $setCookieHeader->toString());
}
public function testSetCookieCanAppendOtherHeadersInWhenCreatingString()
{
$setCookieHeader = new SetCookie();
$setCookieHeader->setName('myname');
$setCookieHeader->setValue('myvalue');
$setCookieHeader->setExpires('Wed, 13-Jan-2021 22:23:01 GMT');
$setCookieHeader->setDomain('docs.foo.com');
$setCookieHeader->setPath('/accounts');
$setCookieHeader->setSecure(true);
$setCookieHeader->setHttponly(true);
$appendCookie = new SetCookie('othername', 'othervalue');
$headerLine = $setCookieHeader->toStringMultipleHeaders([$appendCookie]);
$target = 'Set-Cookie: myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT;'
. ' Domain=docs.foo.com; Path=/accounts;'
. ' Secure; HttpOnly, othername=othervalue';
$this->assertNotEquals($target, $headerLine);
$target = 'Set-Cookie: myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT;'
. ' Domain=docs.foo.com; Path=/accounts;'
. ' Secure; HttpOnly';
$target .= "\n";
$target .= 'Set-Cookie: othername=othervalue';
$this->assertEquals($target, $headerLine);
}
public function testSetCookieAttributesAreUnsettable()
{
$setCookieHeader = new SetCookie();
$setCookieHeader->setName('myname');
$setCookieHeader->setValue('myvalue');
$setCookieHeader->setExpires('Wed, 13-Jan-2021 22:23:01 GMT');
$setCookieHeader->setDomain('docs.foo.com');
$setCookieHeader->setPath('/accounts');
$setCookieHeader->setSecure(true);
$setCookieHeader->setHttponly(true);
$target = 'myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT;'
. ' Domain=docs.foo.com; Path=/accounts;'
. ' Secure; HttpOnly';
$this->assertSame($target, $setCookieHeader->getFieldValue()); // attributes set
$setCookieHeader->setExpires(null);
$setCookieHeader->setDomain(null);
$setCookieHeader->setPath(null);
$setCookieHeader->setSecure(null);
$setCookieHeader->setHttponly(null);
$this->assertSame('myname=myvalue', $setCookieHeader->getFieldValue()); // attributes unset
$setCookieHeader->setValue(null);
$this->assertSame('myname=', $setCookieHeader->getFieldValue());
$this->assertNull($setCookieHeader->getValue());
$this->assertNull($setCookieHeader->getExpires());
$this->assertNull($setCookieHeader->getDomain());
$this->assertNull($setCookieHeader->getPath());
$this->assertNull($setCookieHeader->isSecure());
$this->assertNull($setCookieHeader->isHttponly());
}
public function testSetCookieFieldValueIsEmptyStringWhenNameIsUnset()
{
$setCookieHeader = new SetCookie();
$this->assertSame('', $setCookieHeader->getFieldValue()); // empty
$setCookieHeader->setName('myname');
$setCookieHeader->setValue('myvalue');
$setCookieHeader->setExpires('Wed, 13-Jan-2021 22:23:01 GMT');
$setCookieHeader->setDomain('docs.foo.com');
$setCookieHeader->setPath('/accounts');
$setCookieHeader->setSecure(true);
$setCookieHeader->setHttponly(true);
$target = 'myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT;'
. ' Domain=docs.foo.com; Path=/accounts;'
. ' Secure; HttpOnly';
$this->assertSame($target, $setCookieHeader->getFieldValue()); // not empty
$setCookieHeader->setName(null);
$this->assertSame('', $setCookieHeader->getFieldValue()); // empty again
$this->assertNull($setCookieHeader->getName());
}
public function testSetCookieSetExpiresWithZeroTimeStamp()
{
$setCookieHeader = new SetCookie('myname', 'myvalue', 0);
$this->assertSame('Thu, 01-Jan-1970 00:00:00 GMT', $setCookieHeader->getExpires());
$setCookieHeader = new SetCookie('myname', 'myvalue', 1);
$this->assertSame('Thu, 01-Jan-1970 00:00:01 GMT', $setCookieHeader->getExpires());
$setCookieHeader->setExpires(0);
$this->assertSame('Thu, 01-Jan-1970 00:00:00 GMT', $setCookieHeader->getExpires());
$target = 'myname=myvalue; Expires=Thu, 01-Jan-1970 00:00:00 GMT';
$this->assertSame($target, $setCookieHeader->getFieldValue());
}
public function testSetCookieSetExpiresWithUnixEpochString()
{
$setCookieHeader = new SetCookie('myname', 'myvalue', 'Thu, 01-Jan-1970 00:00:00 GMT');
$this->assertSame('Thu, 01-Jan-1970 00:00:00 GMT', $setCookieHeader->getExpires());
$this->assertSame(0, $setCookieHeader->getExpires(true));
$setCookieHeader = new SetCookie('myname', 'myvalue', 1);
$this->assertSame('Thu, 01-Jan-1970 00:00:01 GMT', $setCookieHeader->getExpires());
$setCookieHeader->setExpires('Thu, 01-Jan-1970 00:00:00 GMT');
$this->assertSame('Thu, 01-Jan-1970 00:00:00 GMT', $setCookieHeader->getExpires());
$this->assertSame(0, $setCookieHeader->getExpires(true));
$target = 'myname=myvalue; Expires=Thu, 01-Jan-1970 00:00:00 GMT';
$this->assertSame($target, $setCookieHeader->getFieldValue());
}
/**
* Check that setCookie does not fail when an expiry date which is bigger
* then 2038 is supplied (effect only 32bit systems)
*/
public function testSetCookieSetExpiresWithStringDateBiggerThen2038()
{
if (PHP_INT_SIZE !== 4) {
$this->markTestSkipped('Testing set cookie expiry which is over 2038 is only relevant on 32bit systems');
return;
}
$setCookieHeader = new SetCookie('myname', 'myvalue', 'Thu, 01-Jan-2040 00:00:00 GMT');
$this->assertSame(2147483647, $setCookieHeader->getExpires(true));
}
public function testIsValidForRequestSubdomainMatch()
{
$setCookieHeader = new SetCookie(
'myname',
'myvalue',
'Wed,
13-Jan-2021 22:23:01 GMT',
'/accounts',
'.foo.com',
true,
true,
99,
9
);
$this->assertTrue($setCookieHeader->isValidForRequest('bar.foo.com', '/accounts', true));
$this->assertFalse(
$setCookieHeader->isValidForRequest('bar.foooo.com', '/accounts', true)
); // false because of domain
$this->assertFalse(
$setCookieHeader->isValidForRequest('bar.foo.com', '/accounts', false)
); // false because of isSecure
$this->assertFalse(
$setCookieHeader->isValidForRequest('bar.foo.com', '/somethingelse', true)
); // false because of path
}
/** Implementation specific tests here */
/**
* @group ZF2-169
*/
public function test169()
{
// @codingStandardsIgnoreStart
$cookie = 'Set-Cookie: leo_auth_token=example; Version=1; Max-Age=1799; Expires=Mon, 20-Feb-2012 02:49:57 GMT; Path=/';
// @codingStandardsIgnoreEnd
$setCookieHeader = SetCookie::fromString($cookie);
$this->assertEquals($cookie, $setCookieHeader->toString());
}
/**
* @group ZF2-169
*/
public function testDoesNotAcceptCookieNameFromArbitraryLocationInHeaderValue()
{
// @codingStandardsIgnoreStart
$cookie = 'Set-Cookie: Version=1; Max-Age=1799; Expires=Mon, 20-Feb-2012 02:49:57 GMT; Path=/; leo_auth_token=example';
// @codingStandardsIgnoreEnd
$setCookieHeader = SetCookie::fromString($cookie);
$this->assertNotEquals('leo_auth_token', $setCookieHeader->getName());
}
public function testGetFieldName()
{
$c = new SetCookie();
$this->assertEquals('Set-Cookie', $c->getFieldName());
}
/**
* @dataProvider validCookieWithInfoProvider
*
* @param string $cStr
* @param array $info
* @param string $expected
*/
public function testGetFieldValue($cStr, array $info, $expected)
{
$cookie = SetCookie::fromString($cStr);
if (! $cookie instanceof SetCookie) {
$this->fail(sprintf('Failed creating a cookie object from \'%s\'', $cStr));
}
$this->assertEquals($expected, $cookie->getFieldValue());
$this->assertEquals($cookie->getFieldName() . ': ' . $expected, $cookie->toString());
}
/**
* @dataProvider validCookieWithInfoProvider
*
* @param string $cStr
* @param array $info
* @param string $expected
*/
public function testToString($cStr, array $info, $expected)
{
$cookie = SetCookie::fromString($cStr);
if (! $cookie instanceof SetCookie) {
$this->fail(sprintf('Failed creating a cookie object from \'%s\'', $cStr));
}
$this->assertEquals($cookie->getFieldName() . ': ' . $expected, $cookie->toString());
}
public function testRfcCompatibility()
{
$name = 'myname';
$value = 'myvalue';
$formatUnquoted = '%s: %s=%s';
$formatQuoted = '%s: %s="%s"';
$cookie = new SetCookie($name, $value);
// default
$this->assertEquals($cookie->toString(), sprintf($formatUnquoted, $cookie->getFieldName(), $name, $value));
// rfc with quote
$cookie->setQuoteFieldValue(true);
$this->assertEquals($cookie->toString(), sprintf($formatQuoted, $cookie->getFieldName(), $name, $value));
// rfc without quote
$cookie->setQuoteFieldValue(false);
$this->assertEquals($cookie->toString(), sprintf($formatUnquoted, $cookie->getFieldName(), $name, $value));
}
public function testSetJsonValue()
{
$cookieName = 'fooCookie';
$jsonData = json_encode(['foo' => 'bar']);
$cookie = new SetCookie($cookieName, $jsonData);
$regExp = sprintf('#^%s=%s#', $cookieName, urlencode($jsonData));
$this->assertRegExp($regExp, $cookie->getFieldValue());
$cookieName = 'fooCookie';
$jsonData = json_encode(['foo' => 'bar']);
$cookie = new SetCookie($cookieName, $jsonData);
$cookie->setDomain('example.org');
$regExp = sprintf('#^%s=%s; Domain=#', $cookieName, urlencode($jsonData));
$this->assertRegExp($regExp, $cookie->getFieldValue());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
SetCookie::fromString("Set-Cookie: leo_auth_token=example;\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$header = new SetCookie('leo_auth_token', "example\r\n\r\nevilContent");
$this->assertEquals('Set-Cookie: leo_auth_token=example%0D%0A%0D%0AevilContent', $header->toString());
}
public function testPreventsCRLFAttackViaSetValue()
{
$header = new SetCookie('leo_auth_token');
$header->setValue("example\r\n\r\nevilContent");
$this->assertEquals('Set-Cookie: leo_auth_token=example%0D%0A%0D%0AevilContent', $header->toString());
}
public function testSetCookieWithEncodeValue()
{
$header = new SetCookie('test');
$header->setValue('a:b');
$this->assertSame('a:b', $header->getValue());
$this->assertSame('test=a%3Ab', $header->getFieldValue());
}
public function testSetCookieWithNoEncodeValue()
{
$header = new SetCookie('test');
$header->setValue('a:b');
$header->setEncodeValue(false);
$this->assertSame('a:b', $header->getValue());
$this->assertSame('test=a:b', $header->getFieldValue());
}
public function setterInjections()
{
return [
'name' => ['setName', "\r\nThis\rIs\nThe\r\nName"],
'domain' => ['setDomain', "\r\nexample\r.\nco\r\n.uk"],
'path' => ['setPath', "\r\n/\rbar\n/foo\r\n/baz"],
];
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*
* @dataProvider setterInjections
*
* @param string $method
* @param string $value
*/
public function testPreventsCRLFAttackViaSetters($method, $value)
{
$header = new SetCookie();
$this->expectException(InvalidArgumentException::class);
$header->{$method}($value);
}
/**
* Provide valid cookie strings with information about them
*
* @return array
*/
public static function validCookieWithInfoProvider()
{
$now = time();
$yesterday = $now - (3600 * 24);
return [
[
'Set-Cookie: justacookie=foo; domain=example.com',
[
'name' => 'justacookie',
'value' => 'foo',
'domain' => 'example.com',
'path' => '/',
'expires' => null,
'secure' => false,
'httponly' => false,
],
'justacookie=foo; Domain=example.com',
],
[
// @codingStandardsIgnoreStart
'Set-Cookie: expires=tomorrow; secure; path=/Space Out/; expires=Tue, 21-Nov-2006 08:33:44 GMT; domain=.example.com',
// @codingStandardsIgnoreEnd
[
'name' => 'expires',
'value' => 'tomorrow',
'domain' => '.example.com',
'path' => '/Space Out/',
'expires' => strtotime('Tue, 21-Nov-2006 08:33:44 GMT'),
'secure' => true,
'httponly' => false,
],
// @codingStandardsIgnoreStart
'expires=tomorrow; Expires=Tue, 21-Nov-2006 08:33:44 GMT; Domain=.example.com; Path=/Space Out/; Secure',
// @codingStandardsIgnoreEnd
],
[
// @codingStandardsIgnoreStart
'Set-Cookie: domain=unittests; expires=' . gmdate('D, d-M-Y H:i:s', $now) . ' GMT; domain=example.com; path=/some%20value/',
// @codingStandardsIgnoreEnd
[
'name' => 'domain',
'value' => 'unittests',
'domain' => 'example.com',
'path' => '/some%20value/',
'expires' => $now,
'secure' => false,
'httponly' => false,
],
// @codingStandardsIgnoreStart
'domain=unittests; Expires=' . gmdate('D, d-M-Y H:i:s', $now) . ' GMT; Domain=example.com; Path=/some%20value/',
// @codingStandardsIgnoreEnd
],
[
// @codingStandardsIgnoreStart
'Set-Cookie: path=indexAction; path=/; domain=.foo.com; expires=' . gmdate('D, d-M-Y H:i:s', $yesterday) . ' GMT',
// @codingStandardsIgnoreEnd
[
'name' => 'path',
'value' => 'indexAction',
'domain' => '.foo.com',
'path' => '/',
'expires' => $yesterday,
'secure' => false,
'httponly' => false,
],
'path=indexAction; Expires=' . gmdate('D, d-M-Y H:i:s', $yesterday) . ' GMT; Domain=.foo.com; Path=/',
],
[
'Set-Cookie: secure=sha1; secure; SECURE; domain=some.really.deep.domain.com',
[
'name' => 'secure',
'value' => 'sha1',
'domain' => 'some.really.deep.domain.com',
'path' => '/',
'expires' => null,
'secure' => true,
'httponly' => false,
],
'secure=sha1; Domain=some.really.deep.domain.com; Secure',
],
[
'Set-Cookie: justacookie=foo; domain=example.com; httpOnly',
[
'name' => 'justacookie',
'value' => 'foo',
'domain' => 'example.com',
'path' => '/',
'expires' => null,
'secure' => false,
'httponly' => true,
],
'justacookie=foo; Domain=example.com; HttpOnly',
],
[
// @codingStandardsIgnoreStart
'Set-Cookie: PHPSESSID=123456789+abcd%2Cef; secure; domain=.localdomain; path=/foo/baz; expires=Tue, 21-Nov-2006 08:33:44 GMT;',
// @codingStandardsIgnoreEnd
[
'name' => 'PHPSESSID',
'value' => '123456789+abcd%2Cef',
'domain' => '.localdomain',
'path' => '/foo/baz',
'expires' => 'Tue, 21-Nov-2006 08:33:44 GMT',
'secure' => true,
'httponly' => false,
],
// @codingStandardsIgnoreStart
'PHPSESSID=123456789+abcd%2Cef; Expires=Tue, 21-Nov-2006 08:33:44 GMT; Domain=.localdomain; Path=/foo/baz; Secure',
// @codingStandardsIgnoreEnd
],
[
// @codingStandardsIgnoreStart
'Set-Cookie: myname=myvalue; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly',
// @codingStandardsIgnoreEnd
[
'name' => 'myname',
'value' => 'myvalue',
'domain' => 'docs.foo.com',
'path' => '/accounts',
'expires' => 'Wed, 13-Jan-2021 22:23:01 GMT',
'secure' => true,
'httponly' => true,
],
// @codingStandardsIgnoreStart
'myname=myvalue; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Domain=docs.foo.com; Path=/accounts; Secure; HttpOnly',
// @codingStandardsIgnoreEnd
],
[
'Set-Cookie:',
[],
'',
],
[
'Set-Cookie: ',
[],
'',
],
[
'Set-Cookie: emptykey= ; Domain=docs.foo.com;',
[
'name' => 'myname',
'value' => '',
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | true |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/RetryAfterTest.php | test/Header/RetryAfterTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\RetryAfter;
class RetryAfterTest extends TestCase
{
public function testRetryAfterFromStringCreatesValidRetryAfterHeader()
{
$retryAfterHeader = RetryAfter::fromString('Retry-After: 10');
$this->assertInstanceOf(HeaderInterface::class, $retryAfterHeader);
$this->assertInstanceOf(RetryAfter::class, $retryAfterHeader);
$this->assertEquals('10', $retryAfterHeader->getDeltaSeconds());
}
public function testRetryAfterFromStringCreatesValidRetryAfterHeaderFromDate()
{
$retryAfterHeader = RetryAfter::fromString('Retry-After: Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $retryAfterHeader->getDate());
}
public function testRetryAfterGetFieldNameReturnsHeaderName()
{
$retryAfterHeader = new RetryAfter();
$this->assertEquals('Retry-After', $retryAfterHeader->getFieldName());
}
public function testRetryAfterGetFieldValueReturnsProperValue()
{
$retryAfterHeader = new RetryAfter();
$retryAfterHeader->setDeltaSeconds(3600);
$this->assertEquals('3600', $retryAfterHeader->getFieldValue());
$retryAfterHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Sun, 06 Nov 1994 08:49:37 GMT', $retryAfterHeader->getFieldValue());
}
public function testRetryAfterToStringReturnsHeaderFormattedString()
{
$retryAfterHeader = new RetryAfter();
$retryAfterHeader->setDeltaSeconds(3600);
$this->assertEquals('Retry-After: 3600', $retryAfterHeader->toString());
$retryAfterHeader->setDate('Sun, 06 Nov 1994 08:49:37 GMT');
$this->assertEquals('Retry-After: Sun, 06 Nov 1994 08:49:37 GMT', $retryAfterHeader->toString());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
RetryAfter::fromString("Retry-After: 10\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/UserAgentTest.php | test/Header/UserAgentTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\UserAgent;
class UserAgentTest extends TestCase
{
public function testUserAgentFromStringCreatesValidUserAgentHeader()
{
$userAgentHeader = UserAgent::fromString('User-Agent: xxx');
$this->assertInstanceOf(HeaderInterface::class, $userAgentHeader);
$this->assertInstanceOf(UserAgent::class, $userAgentHeader);
}
public function testUserAgentGetFieldNameReturnsHeaderName()
{
$userAgentHeader = new UserAgent();
$this->assertEquals('User-Agent', $userAgentHeader->getFieldName());
}
public function testUserAgentGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('UserAgent needs to be completed');
$userAgentHeader = new UserAgent();
$this->assertEquals('xxx', $userAgentHeader->getFieldValue());
}
public function testUserAgentToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('UserAgent needs to be completed');
$userAgentHeader = new UserAgent();
// @todo set some values, then test output
$this->assertEmpty('User-Agent: xxx', $userAgentHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
UserAgent::fromString("User-Agent: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new UserAgent("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentMD5Test.php | test/Header/ContentMD5Test.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\ContentMD5;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class ContentMD5Test extends TestCase
{
public function testContentMD5FromStringCreatesValidContentMD5Header()
{
$contentMD5Header = ContentMD5::fromString('Content-MD5: xxx');
$this->assertInstanceOf(HeaderInterface::class, $contentMD5Header);
$this->assertInstanceOf(ContentMD5::class, $contentMD5Header);
}
public function testContentMD5GetFieldNameReturnsHeaderName()
{
$contentMD5Header = new ContentMD5();
$this->assertEquals('Content-MD5', $contentMD5Header->getFieldName());
}
public function testContentMD5GetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('ContentMD5 needs to be completed');
$contentMD5Header = new ContentMD5();
$this->assertEquals('xxx', $contentMD5Header->getFieldValue());
}
public function testContentMD5ToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('ContentMD5 needs to be completed');
$contentMD5Header = new ContentMD5();
// @todo set some values, then test output
$this->assertEmpty('Content-MD5: xxx', $contentMD5Header->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ContentMD5::fromString("Content-MD5: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new ContentMD5("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/WarningTest.php | test/Header/WarningTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\Warning;
class WarningTest extends TestCase
{
public function testWarningFromStringCreatesValidWarningHeader()
{
$warningHeader = Warning::fromString('Warning: xxx');
$this->assertInstanceOf(HeaderInterface::class, $warningHeader);
$this->assertInstanceOf(Warning::class, $warningHeader);
}
public function testWarningGetFieldNameReturnsHeaderName()
{
$warningHeader = new Warning();
$this->assertEquals('Warning', $warningHeader->getFieldName());
}
public function testWarningGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('Warning needs to be completed');
$warningHeader = new Warning();
$this->assertEquals('xxx', $warningHeader->getFieldValue());
}
public function testWarningToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('Warning needs to be completed');
$warningHeader = new Warning();
// @todo set some values, then test output
$this->assertEmpty('Warning: xxx', $warningHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
Warning::fromString("Warning: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new Warning("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/IfNoneMatchTest.php | test/Header/IfNoneMatchTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\IfNoneMatch;
class IfNoneMatchTest extends TestCase
{
public function testIfNoneMatchFromStringCreatesValidIfNoneMatchHeader()
{
$ifNoneMatchHeader = IfNoneMatch::fromString('If-None-Match: xxx');
$this->assertInstanceOf(HeaderInterface::class, $ifNoneMatchHeader);
$this->assertInstanceOf(IfNoneMatch::class, $ifNoneMatchHeader);
}
public function testIfNoneMatchGetFieldNameReturnsHeaderName()
{
$ifNoneMatchHeader = new IfNoneMatch();
$this->assertEquals('If-None-Match', $ifNoneMatchHeader->getFieldName());
}
public function testIfNoneMatchGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('IfNoneMatch needs to be completed');
$ifNoneMatchHeader = new IfNoneMatch();
$this->assertEquals('xxx', $ifNoneMatchHeader->getFieldValue());
}
public function testIfNoneMatchToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('IfNoneMatch needs to be completed');
$ifNoneMatchHeader = new IfNoneMatch();
// @todo set some values, then test output
$this->assertEmpty('If-None-Match: xxx', $ifNoneMatchHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
IfNoneMatch::fromString("If-None-Match: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new IfNoneMatch("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/OriginTest.php | test/Header/OriginTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\Origin;
use Zend\Uri\Exception\InvalidUriPartException;
class OriginTest extends TestCase
{
/**
* @group 6484
*/
public function testOriginFieldValueIsAlwaysAString()
{
$origin = new Origin();
$this->assertInternalType('string', $origin->getFieldValue());
}
public function testOriginFromStringCreatesValidOriginHeader()
{
$originHeader = Origin::fromString('Origin: http://zend.org');
$this->assertInstanceOf(HeaderInterface::class, $originHeader);
$this->assertInstanceOf(Origin::class, $originHeader);
}
public function testOriginGetFieldNameReturnsHeaderName()
{
$originHeader = new Origin();
$this->assertEquals('Origin', $originHeader->getFieldName());
}
public function testOriginGetFieldValueReturnsProperValue()
{
$originHeader = Origin::fromString('Origin: http://zend.org');
$this->assertEquals('http://zend.org', $originHeader->getFieldValue());
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidUriPartException::class);
Origin::fromString("Origin: http://zend.org\r\n\r\nevilContent");
}
/**
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new Origin("http://zend.org\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentEncodingTest.php | test/Header/ContentEncodingTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\ContentEncoding;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class ContentEncodingTest extends TestCase
{
public function testContentEncodingFromStringCreatesValidContentEncodingHeader()
{
$contentEncodingHeader = ContentEncoding::fromString('Content-Encoding: xxx');
$this->assertInstanceOf(HeaderInterface::class, $contentEncodingHeader);
$this->assertInstanceOf(ContentEncoding::class, $contentEncodingHeader);
}
public function testContentEncodingGetFieldNameReturnsHeaderName()
{
$contentEncodingHeader = new ContentEncoding();
$this->assertEquals('Content-Encoding', $contentEncodingHeader->getFieldName());
}
public function testContentEncodingGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('ContentEncoding needs to be completed');
$contentEncodingHeader = new ContentEncoding();
$this->assertEquals('xxx', $contentEncodingHeader->getFieldValue());
}
public function testContentEncodingToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('ContentEncoding needs to be completed');
$contentEncodingHeader = new ContentEncoding();
// @todo set some values, then test output
$this->assertEmpty('Content-Encoding: xxx', $contentEncodingHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ContentEncoding::fromString("Content-Encoding: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new ContentEncoding("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/TETest.php | test/Header/TETest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\TE;
class TETest extends TestCase
{
public function testTEFromStringCreatesValidTEHeader()
{
$tEHeader = TE::fromString('TE: xxx');
$this->assertInstanceOf(HeaderInterface::class, $tEHeader);
$this->assertInstanceOf(TE::class, $tEHeader);
}
public function testTEGetFieldNameReturnsHeaderName()
{
$tEHeader = new TE();
$this->assertEquals('TE', $tEHeader->getFieldName());
}
public function testTEGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('TE needs to be completed');
$tEHeader = new TE();
$this->assertEquals('xxx', $tEHeader->getFieldValue());
}
public function testTEToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('TE needs to be completed');
$tEHeader = new TE();
// @todo set some values, then test output
$this->assertEmpty('TE: xxx', $tEHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
TE::fromString("TE: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new TE("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/IfMatchTest.php | test/Header/IfMatchTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\IfMatch;
class IfMatchTest extends TestCase
{
public function testIfMatchFromStringCreatesValidIfMatchHeader()
{
$ifMatchHeader = IfMatch::fromString('If-Match: xxx');
$this->assertInstanceOf(HeaderInterface::class, $ifMatchHeader);
$this->assertInstanceOf(IfMatch::class, $ifMatchHeader);
}
public function testIfMatchGetFieldNameReturnsHeaderName()
{
$ifMatchHeader = new IfMatch();
$this->assertEquals('If-Match', $ifMatchHeader->getFieldName());
}
public function testIfMatchGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('IfMatch needs to be completed');
$ifMatchHeader = new IfMatch();
$this->assertEquals('xxx', $ifMatchHeader->getFieldValue());
}
public function testIfMatchToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('IfMatch needs to be completed');
$ifMatchHeader = new IfMatch();
// @todo set some values, then test output
$this->assertEmpty('If-Match: xxx', $ifMatchHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
IfMatch::fromString("If-Match: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new IfMatch("xxx\r\n\r\nevilContent");
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
zendframework/zend-http | https://github.com/zendframework/zend-http/blob/ac4ffd09d509b2c5c0285178c4f7de740f05c3d9/test/Header/ContentLengthTest.php | test/Header/ContentLengthTest.php | <?php
/**
* @see https://github.com/zendframework/zend-http for the canonical source repository
* @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
*/
namespace ZendTest\Http\Header;
use PHPUnit\Framework\TestCase;
use Zend\Http\Header\ContentLength;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
class ContentLengthTest extends TestCase
{
public function testContentLengthFromStringCreatesValidContentLengthHeader()
{
$contentLengthHeader = ContentLength::fromString('Content-Length: xxx');
$this->assertInstanceOf(HeaderInterface::class, $contentLengthHeader);
$this->assertInstanceOf(ContentLength::class, $contentLengthHeader);
}
public function testContentLengthGetFieldNameReturnsHeaderName()
{
$contentLengthHeader = new ContentLength();
$this->assertEquals('Content-Length', $contentLengthHeader->getFieldName());
}
public function testContentLengthGetFieldValueReturnsProperValue()
{
$this->markTestIncomplete('ContentLength needs to be completed');
$contentLengthHeader = new ContentLength();
$this->assertEquals('xxx', $contentLengthHeader->getFieldValue());
}
public function testContentLengthToStringReturnsHeaderFormattedString()
{
$this->markTestIncomplete('ContentLength needs to be completed');
$contentLengthHeader = new ContentLength();
// @todo set some values, then test output
$this->assertEmpty('Content-Length: xxx', $contentLengthHeader->toString());
}
/** Implementation specific tests here */
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaFromString()
{
$this->expectException(InvalidArgumentException::class);
ContentLength::fromString("Content-Length: xxx\r\n\r\nevilContent");
}
/**
* @see http://en.wikipedia.org/wiki/HTTP_response_splitting
* @group ZF2015-04
*/
public function testPreventsCRLFAttackViaConstructor()
{
$this->expectException(InvalidArgumentException::class);
new ContentLength("Content-Length: xxx\r\n\r\nevilContent");
}
public function testZeroValue()
{
$contentLengthHeader = new ContentLength(0);
$this->assertEquals(0, $contentLengthHeader->getFieldValue());
$this->assertEquals('Content-Length: 0', $contentLengthHeader->toString());
}
}
| php | BSD-3-Clause | ac4ffd09d509b2c5c0285178c4f7de740f05c3d9 | 2026-01-05T05:18:13.309357Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.