git-svn-id: https://msi/svn/firstRepo/Service/branches/Slim3@40 0f545695-f87b-41b6-9a03-7f16563b5454
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim Framework (http://slimframework.com)
|
||||
*
|
||||
* @link https://github.com/slimphp/Slim
|
||||
* @copyright Copyright (c) 2011-2015 Josh Lockhart
|
||||
* @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
/**
|
||||
* Body
|
||||
*
|
||||
* This class represents an HTTP message body and encapsulates a
|
||||
* streamable resource according to the PSR-7 standard.
|
||||
*
|
||||
* @link https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php
|
||||
*/
|
||||
class Body extends Stream
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim Framework (http://slimframework.com)
|
||||
*
|
||||
* @link https://github.com/slimphp/Slim
|
||||
* @copyright Copyright (c) 2011-2015 Josh Lockhart
|
||||
* @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
use Slim\Collection;
|
||||
use Slim\Interfaces\Http\EnvironmentInterface;
|
||||
|
||||
/**
|
||||
* Environment
|
||||
*
|
||||
* This class decouples the Slim application from the global PHP environment.
|
||||
* This is particularly useful for unit testing, but it also lets us create
|
||||
* custom sub-requests.
|
||||
*/
|
||||
class Environment extends Collection implements EnvironmentInterface
|
||||
{
|
||||
/**
|
||||
* Create mock environment
|
||||
*
|
||||
* @param array $userData Array of custom environment keys and values
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public static function mock(array $userData = [])
|
||||
{
|
||||
$data = array_merge([
|
||||
'SERVER_PROTOCOL' => 'HTTP/1.1',
|
||||
'REQUEST_METHOD' => 'GET',
|
||||
'SCRIPT_NAME' => '',
|
||||
'REQUEST_URI' => '',
|
||||
'QUERY_STRING' => '',
|
||||
'SERVER_NAME' => 'localhost',
|
||||
'SERVER_PORT' => 80,
|
||||
'HTTP_HOST' => 'localhost',
|
||||
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
||||
'HTTP_ACCEPT_LANGUAGE' => 'en-US,en;q=0.8',
|
||||
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
|
||||
'HTTP_USER_AGENT' => 'Slim Framework',
|
||||
'REMOTE_ADDR' => '127.0.0.1',
|
||||
'REQUEST_TIME' => time(),
|
||||
'REQUEST_TIME_FLOAT' => microtime(true),
|
||||
], $userData);
|
||||
|
||||
return new static($data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim Framework (http://slimframework.com)
|
||||
*
|
||||
* @link https://github.com/slimphp/Slim
|
||||
* @copyright Copyright (c) 2011-2015 Josh Lockhart
|
||||
* @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Abstract message (base class for Request and Response)
|
||||
*
|
||||
* This class represents a general HTTP message. It provides common properties and methods for
|
||||
* the HTTP request and response, as defined in the PSR-7 MessageInterface.
|
||||
*
|
||||
* @link https://github.com/php-fig/http-message/blob/master/src/MessageInterface.php
|
||||
* @see Slim\Http\Request
|
||||
* @see Slim\Http\Response
|
||||
*/
|
||||
abstract class Message implements MessageInterface
|
||||
{
|
||||
/**
|
||||
* Protocol version
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $protocolVersion = '1.1';
|
||||
|
||||
/**
|
||||
* Headers
|
||||
*
|
||||
* @var \Slim\Interfaces\Http\HeadersInterface
|
||||
*/
|
||||
protected $headers;
|
||||
|
||||
/**
|
||||
* Body object
|
||||
*
|
||||
* @var \Psr\Http\Message\StreamInterface
|
||||
*/
|
||||
protected $body;
|
||||
|
||||
|
||||
/**
|
||||
* Disable magic setter to ensure immutability
|
||||
*/
|
||||
public function __set($name, $value)
|
||||
{
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
* Protocol
|
||||
******************************************************************************/
|
||||
|
||||
/**
|
||||
* Retrieves the HTTP protocol version as a string.
|
||||
*
|
||||
* The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
|
||||
*
|
||||
* @return string HTTP protocol version.
|
||||
*/
|
||||
public function getProtocolVersion()
|
||||
{
|
||||
return $this->protocolVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified HTTP protocol version.
|
||||
*
|
||||
* The version string MUST contain only the HTTP version number (e.g.,
|
||||
* "1.1", "1.0").
|
||||
*
|
||||
* This method MUST be implemented in such a way as to retain the
|
||||
* immutability of the message, and MUST return an instance that has the
|
||||
* new protocol version.
|
||||
*
|
||||
* @param string $version HTTP protocol version
|
||||
* @return static
|
||||
* @throws InvalidArgumentException if the http version is an invalid number
|
||||
*/
|
||||
public function withProtocolVersion($version)
|
||||
{
|
||||
static $valid = [
|
||||
'1.0' => true,
|
||||
'1.1' => true,
|
||||
'2.0' => true,
|
||||
];
|
||||
if (!isset($valid[$version])) {
|
||||
throw new InvalidArgumentException('Invalid HTTP version. Must be one of: 1.0, 1.1, 2.0');
|
||||
}
|
||||
$clone = clone $this;
|
||||
$clone->protocolVersion = $version;
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
* Headers
|
||||
******************************************************************************/
|
||||
|
||||
/**
|
||||
* Retrieves all message header values.
|
||||
*
|
||||
* The keys represent the header name as it will be sent over the wire, and
|
||||
* each value is an array of strings associated with the header.
|
||||
*
|
||||
* // Represent the headers as a string
|
||||
* foreach ($message->getHeaders() as $name => $values) {
|
||||
* echo $name . ": " . implode(", ", $values);
|
||||
* }
|
||||
*
|
||||
* // Emit headers iteratively:
|
||||
* foreach ($message->getHeaders() as $name => $values) {
|
||||
* foreach ($values as $value) {
|
||||
* header(sprintf('%s: %s', $name, $value), false);
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* While header names are not case-sensitive, getHeaders() will preserve the
|
||||
* exact case in which headers were originally specified.
|
||||
*
|
||||
* @return array Returns an associative array of the message's headers. Each
|
||||
* key MUST be a header name, and each value MUST be an array of strings
|
||||
* for that header.
|
||||
*/
|
||||
public function getHeaders()
|
||||
{
|
||||
return $this->headers->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a header exists by the given case-insensitive name.
|
||||
*
|
||||
* @param string $name Case-insensitive header field name.
|
||||
* @return bool Returns true if any header names match the given header
|
||||
* name using a case-insensitive string comparison. Returns false if
|
||||
* no matching header name is found in the message.
|
||||
*/
|
||||
public function hasHeader($name)
|
||||
{
|
||||
return $this->headers->has($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a message header value by the given case-insensitive name.
|
||||
*
|
||||
* This method returns an array of all the header values of the given
|
||||
* case-insensitive header name.
|
||||
*
|
||||
* If the header does not appear in the message, this method MUST return an
|
||||
* empty array.
|
||||
*
|
||||
* @param string $name Case-insensitive header field name.
|
||||
* @return string[] An array of string values as provided for the given
|
||||
* header. If the header does not appear in the message, this method MUST
|
||||
* return an empty array.
|
||||
*/
|
||||
public function getHeader($name)
|
||||
{
|
||||
return $this->headers->get($name, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a comma-separated string of the values for a single header.
|
||||
*
|
||||
* This method returns all of the header values of the given
|
||||
* case-insensitive header name as a string concatenated together using
|
||||
* a comma.
|
||||
*
|
||||
* NOTE: Not all header values may be appropriately represented using
|
||||
* comma concatenation. For such headers, use getHeader() instead
|
||||
* and supply your own delimiter when concatenating.
|
||||
*
|
||||
* If the header does not appear in the message, this method MUST return
|
||||
* an empty string.
|
||||
*
|
||||
* @param string $name Case-insensitive header field name.
|
||||
* @return string A string of values as provided for the given header
|
||||
* concatenated together using a comma. If the header does not appear in
|
||||
* the message, this method MUST return an empty string.
|
||||
*/
|
||||
public function getHeaderLine($name)
|
||||
{
|
||||
return implode(',', $this->headers->get($name, []));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the provided value replacing the specified header.
|
||||
*
|
||||
* While header names are case-insensitive, the casing of the header will
|
||||
* be preserved by this function, and returned from getHeaders().
|
||||
*
|
||||
* This method MUST be implemented in such a way as to retain the
|
||||
* immutability of the message, and MUST return an instance that has the
|
||||
* new and/or updated header and value.
|
||||
*
|
||||
* @param string $name Case-insensitive header field name.
|
||||
* @param string|string[] $value Header value(s).
|
||||
* @return static
|
||||
* @throws \InvalidArgumentException for invalid header names or values.
|
||||
*/
|
||||
public function withHeader($name, $value)
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->headers->set($name, $value);
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified header appended with the given value.
|
||||
*
|
||||
* Existing values for the specified header will be maintained. The new
|
||||
* value(s) will be appended to the existing list. If the header did not
|
||||
* exist previously, it will be added.
|
||||
*
|
||||
* This method MUST be implemented in such a way as to retain the
|
||||
* immutability of the message, and MUST return an instance that has the
|
||||
* new header and/or value.
|
||||
*
|
||||
* @param string $name Case-insensitive header field name to add.
|
||||
* @param string|string[] $value Header value(s).
|
||||
* @return static
|
||||
* @throws \InvalidArgumentException for invalid header names or values.
|
||||
*/
|
||||
public function withAddedHeader($name, $value)
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->headers->add($name, $value);
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance without the specified header.
|
||||
*
|
||||
* Header resolution MUST be done without case-sensitivity.
|
||||
*
|
||||
* This method MUST be implemented in such a way as to retain the
|
||||
* immutability of the message, and MUST return an instance that removes
|
||||
* the named header.
|
||||
*
|
||||
* @param string $name Case-insensitive header field name to remove.
|
||||
* @return static
|
||||
*/
|
||||
public function withoutHeader($name)
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->headers->remove($name);
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/*******************************************************************************
|
||||
* Body
|
||||
******************************************************************************/
|
||||
|
||||
/**
|
||||
* Gets the body of the message.
|
||||
*
|
||||
* @return StreamInterface Returns the body as a stream.
|
||||
*/
|
||||
public function getBody()
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified message body.
|
||||
*
|
||||
* The body MUST be a StreamInterface object.
|
||||
*
|
||||
* This method MUST be implemented in such a way as to retain the
|
||||
* immutability of the message, and MUST return a new instance that has the
|
||||
* new body stream.
|
||||
*
|
||||
* @param StreamInterface $body Body.
|
||||
* @return static
|
||||
* @throws \InvalidArgumentException When the body is not valid.
|
||||
*/
|
||||
public function withBody(StreamInterface $body)
|
||||
{
|
||||
// TODO: Test for invalid body?
|
||||
$clone = clone $this;
|
||||
$clone->body = $body;
|
||||
|
||||
return $clone;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim Framework (http://slimframework.com)
|
||||
*
|
||||
* @link https://github.com/slimphp/Slim
|
||||
* @copyright Copyright (c) 2011-2015 Josh Lockhart
|
||||
* @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
/**
|
||||
* Provides a PSR-7 implementation of a reusable raw request body
|
||||
*/
|
||||
class RequestBody extends Body
|
||||
{
|
||||
/**
|
||||
* Create a new RequestBody.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$stream = fopen('php://temp', 'w+');
|
||||
stream_copy_to_stream(fopen('php://input', 'r'), $stream);
|
||||
rewind($stream);
|
||||
|
||||
parent::__construct($stream);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim Framework (http://slimframework.com)
|
||||
*
|
||||
* @link https://github.com/slimphp/Slim
|
||||
* @copyright Copyright (c) 2011-2015 Josh Lockhart
|
||||
* @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Represents a data stream as defined in PSR-7.
|
||||
*
|
||||
* @link https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php
|
||||
*/
|
||||
class Stream implements StreamInterface
|
||||
{
|
||||
/**
|
||||
* Resource modes
|
||||
*
|
||||
* @var array
|
||||
* @link http://php.net/manual/function.fopen.php
|
||||
*/
|
||||
protected static $modes = [
|
||||
'readable' => ['r', 'r+', 'w+', 'a+', 'x+', 'c+'],
|
||||
'writable' => ['r+', 'w', 'w+', 'a', 'a+', 'x', 'x+', 'c', 'c+'],
|
||||
];
|
||||
|
||||
/**
|
||||
* The underlying stream resource
|
||||
*
|
||||
* @var resource
|
||||
*/
|
||||
protected $stream;
|
||||
|
||||
/**
|
||||
* Stream metadata
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $meta;
|
||||
|
||||
/**
|
||||
* Is this stream readable?
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $readable;
|
||||
|
||||
/**
|
||||
* Is this stream writable?
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $writable;
|
||||
|
||||
/**
|
||||
* Is this stream seekable?
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $seekable;
|
||||
|
||||
/**
|
||||
* The size of the stream if known
|
||||
*
|
||||
* @var null|int
|
||||
*/
|
||||
protected $size;
|
||||
|
||||
/**
|
||||
* Create a new Stream.
|
||||
*
|
||||
* @param resource $stream A PHP resource handle.
|
||||
*
|
||||
* @throws InvalidArgumentException If argument is not a resource.
|
||||
*/
|
||||
public function __construct($stream)
|
||||
{
|
||||
$this->attach($stream);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get stream metadata as an associative array or retrieve a specific key.
|
||||
*
|
||||
* The keys returned are identical to the keys returned from PHP's
|
||||
* stream_get_meta_data() function.
|
||||
*
|
||||
* @link http://php.net/manual/en/function.stream-get-meta-data.php
|
||||
*
|
||||
* @param string $key Specific metadata to retrieve.
|
||||
*
|
||||
* @return array|mixed|null Returns an associative array if no key is
|
||||
* provided. Returns a specific key value if a key is provided and the
|
||||
* value is found, or null if the key is not found.
|
||||
*/
|
||||
public function getMetadata($key = null)
|
||||
{
|
||||
$this->meta = stream_get_meta_data($this->stream);
|
||||
if (is_null($key) === true) {
|
||||
return $this->meta;
|
||||
}
|
||||
|
||||
return isset($this->meta[$key]) ? $this->meta[$key] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is a resource attached to this stream?
|
||||
*
|
||||
* Note: This method is not part of the PSR-7 standard.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function isAttached()
|
||||
{
|
||||
return is_resource($this->stream);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach new resource to this object.
|
||||
*
|
||||
* Note: This method is not part of the PSR-7 standard.
|
||||
*
|
||||
* @param resource $newStream A PHP resource handle.
|
||||
*
|
||||
* @throws InvalidArgumentException If argument is not a valid PHP resource.
|
||||
*/
|
||||
protected function attach($newStream)
|
||||
{
|
||||
if (is_resource($newStream) === false) {
|
||||
throw new InvalidArgumentException(__METHOD__ . ' argument must be a valid PHP resource');
|
||||
}
|
||||
|
||||
if ($this->isAttached() === true) {
|
||||
$this->detach();
|
||||
}
|
||||
|
||||
$this->stream = $newStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Separates any underlying resources from the stream.
|
||||
*
|
||||
* After the stream has been detached, the stream is in an unusable state.
|
||||
*
|
||||
* @return resource|null Underlying PHP stream, if any
|
||||
*/
|
||||
public function detach()
|
||||
{
|
||||
$oldResource = $this->stream;
|
||||
$this->stream = null;
|
||||
$this->meta = null;
|
||||
$this->readable = null;
|
||||
$this->writable = null;
|
||||
$this->seekable = null;
|
||||
$this->size = null;
|
||||
|
||||
return $oldResource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all data from the stream into a string, from the beginning to end.
|
||||
*
|
||||
* This method MUST attempt to seek to the beginning of the stream before
|
||||
* reading data and read the stream until the end is reached.
|
||||
*
|
||||
* Warning: This could attempt to load a large amount of data into memory.
|
||||
*
|
||||
* This method MUST NOT raise an exception in order to conform with PHP's
|
||||
* string casting operations.
|
||||
*
|
||||
* @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
|
||||
* @return string
|
||||
*/
|
||||
public function __toString()
|
||||
{
|
||||
if (!$this->isAttached()) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
$this->rewind();
|
||||
return $this->getContents();
|
||||
} catch (RuntimeException $e) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the stream and any underlying resources.
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
if ($this->isAttached() === true) {
|
||||
fclose($this->stream);
|
||||
}
|
||||
|
||||
$this->detach();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the size of the stream if known.
|
||||
*
|
||||
* @return int|null Returns the size in bytes if known, or null if unknown.
|
||||
*/
|
||||
public function getSize()
|
||||
{
|
||||
if (!$this->size && $this->isAttached() === true) {
|
||||
$stats = fstat($this->stream);
|
||||
$this->size = isset($stats['size']) ? $stats['size'] : null;
|
||||
}
|
||||
|
||||
return $this->size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current position of the file read/write pointer
|
||||
*
|
||||
* @return int Position of the file pointer
|
||||
*
|
||||
* @throws RuntimeException on error.
|
||||
*/
|
||||
public function tell()
|
||||
{
|
||||
if (!$this->isAttached() || ($position = ftell($this->stream)) === false) {
|
||||
throw new RuntimeException('Could not get the position of the pointer in stream');
|
||||
}
|
||||
|
||||
return $position;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the stream is at the end of the stream.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function eof()
|
||||
{
|
||||
return $this->isAttached() ? feof($this->stream) : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether or not the stream is readable.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isReadable()
|
||||
{
|
||||
if ($this->readable === null) {
|
||||
$this->readable = false;
|
||||
if ($this->isAttached()) {
|
||||
$meta = $this->getMetadata();
|
||||
foreach (self::$modes['readable'] as $mode) {
|
||||
if (strpos($meta['mode'], $mode) === 0) {
|
||||
$this->readable = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->readable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether or not the stream is writable.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isWritable()
|
||||
{
|
||||
if ($this->writable === null) {
|
||||
$this->writable = false;
|
||||
if ($this->isAttached()) {
|
||||
$meta = $this->getMetadata();
|
||||
foreach (self::$modes['writable'] as $mode) {
|
||||
if (strpos($meta['mode'], $mode) === 0) {
|
||||
$this->writable = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->writable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether or not the stream is seekable.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isSeekable()
|
||||
{
|
||||
if ($this->seekable === null) {
|
||||
$this->seekable = false;
|
||||
if ($this->isAttached()) {
|
||||
$meta = $this->getMetadata();
|
||||
$this->seekable = $meta['seekable'];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->seekable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seek to a position in the stream.
|
||||
*
|
||||
* @link http://www.php.net/manual/en/function.fseek.php
|
||||
*
|
||||
* @param int $offset Stream offset
|
||||
* @param int $whence Specifies how the cursor position will be calculated
|
||||
* based on the seek offset. Valid values are identical to the built-in
|
||||
* PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
|
||||
* offset bytes SEEK_CUR: Set position to current location plus offset
|
||||
* SEEK_END: Set position to end-of-stream plus offset.
|
||||
*
|
||||
* @throws RuntimeException on failure.
|
||||
*/
|
||||
public function seek($offset, $whence = SEEK_SET)
|
||||
{
|
||||
// Note that fseek returns 0 on success!
|
||||
if (!$this->isSeekable() || fseek($this->stream, $offset, $whence) === -1) {
|
||||
throw new RuntimeException('Could not seek in stream');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Seek to the beginning of the stream.
|
||||
*
|
||||
* If the stream is not seekable, this method will raise an exception;
|
||||
* otherwise, it will perform a seek(0).
|
||||
*
|
||||
* @see seek()
|
||||
*
|
||||
* @link http://www.php.net/manual/en/function.fseek.php
|
||||
*
|
||||
* @throws RuntimeException on failure.
|
||||
*/
|
||||
public function rewind()
|
||||
{
|
||||
if (!$this->isSeekable() || rewind($this->stream) === false) {
|
||||
throw new RuntimeException('Could not rewind stream');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read data from the stream.
|
||||
*
|
||||
* @param int $length Read up to $length bytes from the object and return
|
||||
* them. Fewer than $length bytes may be returned if underlying stream
|
||||
* call returns fewer bytes.
|
||||
*
|
||||
* @return string Returns the data read from the stream, or an empty string
|
||||
* if no bytes are available.
|
||||
*
|
||||
* @throws RuntimeException if an error occurs.
|
||||
*/
|
||||
public function read($length)
|
||||
{
|
||||
if (!$this->isReadable() || ($data = fread($this->stream, $length)) === false) {
|
||||
throw new RuntimeException('Could not read from stream');
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to the stream.
|
||||
*
|
||||
* @param string $string The string that is to be written.
|
||||
*
|
||||
* @return int Returns the number of bytes written to the stream.
|
||||
*
|
||||
* @throws RuntimeException on failure.
|
||||
*/
|
||||
public function write($string)
|
||||
{
|
||||
if (!$this->isWritable() || ($written = fwrite($this->stream, $string)) === false) {
|
||||
throw new RuntimeException('Could not write to stream');
|
||||
}
|
||||
|
||||
// reset size so that it will be recalculated on next call to getSize()
|
||||
$this->size = null;
|
||||
|
||||
return $written;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the remaining contents in a string
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws RuntimeException if unable to read or an error occurs while
|
||||
* reading.
|
||||
*/
|
||||
public function getContents()
|
||||
{
|
||||
if (!$this->isReadable() || ($contents = stream_get_contents($this->stream)) === false) {
|
||||
throw new RuntimeException('Could not get contents of stream');
|
||||
}
|
||||
|
||||
return $contents;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim Framework (http://slimframework.com)
|
||||
*
|
||||
* @link https://github.com/slimphp/Slim
|
||||
* @copyright Copyright (c) 2011-2015 Josh Lockhart
|
||||
* @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
use RuntimeException;
|
||||
use InvalidArgumentException;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
|
||||
/**
|
||||
* Represents Uploaded Files.
|
||||
*
|
||||
* It manages and normalizes uploaded files according to the PSR-7 standard.
|
||||
*
|
||||
* @link https://github.com/php-fig/http-message/blob/master/src/UploadedFileInterface.php
|
||||
* @link https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php
|
||||
*/
|
||||
class UploadedFile implements UploadedFileInterface
|
||||
{
|
||||
/**
|
||||
* The client-provided file name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name;
|
||||
/**
|
||||
* The client-provided media type of the file.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $type;
|
||||
/**
|
||||
* The size of the file in bytes.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $size;
|
||||
/**
|
||||
* A valid PHP UPLOAD_ERR_xxx code for the file upload.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $error = UPLOAD_ERR_OK;
|
||||
/**
|
||||
* Indicates if the upload is from a SAPI environment.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $sapi = false;
|
||||
/**
|
||||
* An optional StreamInterface wrapping the file resource.
|
||||
*
|
||||
* @var StreamInterface
|
||||
*/
|
||||
protected $stream;
|
||||
/**
|
||||
* Indicates if the uploaded file has already been moved.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $moved = false;
|
||||
|
||||
/**
|
||||
* Create a normalized tree of UploadedFile instances from the Environment.
|
||||
*
|
||||
* @param Environment $env The environment
|
||||
*
|
||||
* @return array|null A normalized tree of UploadedFile instances or null if none are provided.
|
||||
*/
|
||||
public static function createFromEnvironment(Environment $env)
|
||||
{
|
||||
if (is_array($env['slim.files']) && $env->has('slim.files')) {
|
||||
return $env['slim.files'];
|
||||
} elseif (isset($_FILES)) {
|
||||
return static::parseUploadedFiles($_FILES);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a non-normalized, i.e. $_FILES superglobal, tree of uploaded file data.
|
||||
*
|
||||
* @param array $uploadedFiles The non-normalized tree of uploaded file data.
|
||||
*
|
||||
* @return array A normalized tree of UploadedFile instances.
|
||||
*/
|
||||
private static function parseUploadedFiles(array $uploadedFiles)
|
||||
{
|
||||
$parsed = [];
|
||||
foreach ($uploadedFiles as $field => $uploadedFile) {
|
||||
if (!isset($uploadedFile['error'])) {
|
||||
if (is_array($uploadedFile)) {
|
||||
$parsed[$field] = static::parseUploadedFiles($uploadedFile);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$parsed[$field] = [];
|
||||
if (!is_array($uploadedFile['error'])) {
|
||||
$parsed[$field] = new static(
|
||||
$uploadedFile['tmp_name'],
|
||||
isset($uploadedFile['tmp_name']) ? $uploadedFile['name'] : null,
|
||||
isset($uploadedFile['type']) ? $uploadedFile['type'] : null,
|
||||
isset($uploadedFile['size']) ? $uploadedFile['size'] : null,
|
||||
$uploadedFile['error'],
|
||||
true
|
||||
);
|
||||
} else {
|
||||
foreach ($uploadedFile['error'] as $fileIdx => $error) {
|
||||
$parsed[$field][] = new static(
|
||||
$uploadedFile['tmp_name'][$fileIdx],
|
||||
isset($uploadedFile['tmp_name']) ? $uploadedFile['name'][$fileIdx] : null,
|
||||
isset($uploadedFile['type']) ? $uploadedFile['type'][$fileIdx] : null,
|
||||
isset($uploadedFile['size']) ? $uploadedFile['size'][$fileIdx] : null,
|
||||
$uploadedFile['error'][$fileIdx],
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a new UploadedFile instance.
|
||||
*
|
||||
* @param string $file The full path to the uploaded file provided by the client.
|
||||
* @param string|null $name The file name.
|
||||
* @param string|null $type The file media type.
|
||||
* @param int|null $size The file size in bytes.
|
||||
* @param int $error The UPLOAD_ERR_XXX code representing the status of the upload.
|
||||
* @param bool $sapi Indicates if the upload is in a SAPI environment.
|
||||
*/
|
||||
public function __construct($file, $name = null, $type = null, $size = null, $error = UPLOAD_ERR_OK, $sapi = false)
|
||||
{
|
||||
$this->file = $file;
|
||||
$this->name = $name;
|
||||
$this->type = $type;
|
||||
$this->size = $size;
|
||||
$this->error = $error;
|
||||
$this->sapi = $sapi;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a stream representing the uploaded file.
|
||||
*
|
||||
* This method MUST return a StreamInterface instance, representing the
|
||||
* uploaded file. The purpose of this method is to allow utilizing native PHP
|
||||
* stream functionality to manipulate the file upload, such as
|
||||
* stream_copy_to_stream() (though the result will need to be decorated in a
|
||||
* native PHP stream wrapper to work with such functions).
|
||||
*
|
||||
* If the moveTo() method has been called previously, this method MUST raise
|
||||
* an exception.
|
||||
*
|
||||
* @return StreamInterface Stream representation of the uploaded file.
|
||||
* @throws \RuntimeException in cases when no stream is available or can be
|
||||
* created.
|
||||
*/
|
||||
public function getStream()
|
||||
{
|
||||
if ($this->moved) {
|
||||
throw new \RuntimeException(sprintf('Uploaded file %1s has already been moved', $this->name));
|
||||
}
|
||||
if ($this->stream === null) {
|
||||
$this->stream = new Stream(fopen($this->file, 'r'));
|
||||
}
|
||||
|
||||
return $this->stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the uploaded file to a new location.
|
||||
*
|
||||
* Use this method as an alternative to move_uploaded_file(). This method is
|
||||
* guaranteed to work in both SAPI and non-SAPI environments.
|
||||
* Implementations must determine which environment they are in, and use the
|
||||
* appropriate method (move_uploaded_file(), rename(), or a stream
|
||||
* operation) to perform the operation.
|
||||
*
|
||||
* $targetPath may be an absolute path, or a relative path. If it is a
|
||||
* relative path, resolution should be the same as used by PHP's rename()
|
||||
* function.
|
||||
*
|
||||
* The original file or stream MUST be removed on completion.
|
||||
*
|
||||
* If this method is called more than once, any subsequent calls MUST raise
|
||||
* an exception.
|
||||
*
|
||||
* When used in an SAPI environment where $_FILES is populated, when writing
|
||||
* files via moveTo(), is_uploaded_file() and move_uploaded_file() SHOULD be
|
||||
* used to ensure permissions and upload status are verified correctly.
|
||||
*
|
||||
* If you wish to move to a stream, use getStream(), as SAPI operations
|
||||
* cannot guarantee writing to stream destinations.
|
||||
*
|
||||
* @see http://php.net/is_uploaded_file
|
||||
* @see http://php.net/move_uploaded_file
|
||||
*
|
||||
* @param string $targetPath Path to which to move the uploaded file.
|
||||
*
|
||||
* @throws InvalidArgumentException if the $path specified is invalid.
|
||||
* @throws RuntimeException on any error during the move operation, or on
|
||||
* the second or subsequent call to the method.
|
||||
*/
|
||||
public function moveTo($targetPath)
|
||||
{
|
||||
if ($this->moved) {
|
||||
throw new RuntimeException('Uploaded file already moved');
|
||||
}
|
||||
|
||||
if (!is_writable(dirname($targetPath))) {
|
||||
throw new InvalidArgumentException('Upload target path is not writable');
|
||||
}
|
||||
|
||||
$targetIsStream = strpos($targetPath, '://') > 0;
|
||||
if ($targetIsStream) {
|
||||
if (!copy($this->file, $targetPath)) {
|
||||
throw new RuntimeException(sprintf('Error moving uploaded file %1s to %2s', $this->name, $targetPath));
|
||||
}
|
||||
if (!unlink($this->file)) {
|
||||
throw new RuntimeException(sprintf('Error removing uploaded file %1s', $this->name));
|
||||
}
|
||||
} elseif ($this->sapi) {
|
||||
if (!is_uploaded_file($this->file)) {
|
||||
throw new RuntimeException(sprintf('%1s is not a valid uploaded file', $this->file));
|
||||
}
|
||||
|
||||
if (!move_uploaded_file($this->file, $targetPath)) {
|
||||
throw new RuntimeException(sprintf('Error moving uploaded file %1s to %2s', $this->name, $targetPath));
|
||||
}
|
||||
} else {
|
||||
if (!rename($this->file, $targetPath)) {
|
||||
throw new RuntimeException(sprintf('Error moving uploaded file %1s to %2s', $this->name, $targetPath));
|
||||
}
|
||||
}
|
||||
|
||||
$this->moved = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the error associated with the uploaded file.
|
||||
*
|
||||
* The return value MUST be one of PHP's UPLOAD_ERR_XXX constants.
|
||||
*
|
||||
* If the file was uploaded successfully, this method MUST return
|
||||
* UPLOAD_ERR_OK.
|
||||
*
|
||||
* Implementations SHOULD return the value stored in the "error" key of
|
||||
* the file in the $_FILES array.
|
||||
*
|
||||
* @see http://php.net/manual/en/features.file-upload.errors.php
|
||||
*
|
||||
* @return int One of PHP's UPLOAD_ERR_XXX constants.
|
||||
*/
|
||||
public function getError()
|
||||
{
|
||||
return $this->error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the filename sent by the client.
|
||||
*
|
||||
* Do not trust the value returned by this method. A client could send
|
||||
* a malicious filename with the intention to corrupt or hack your
|
||||
* application.
|
||||
*
|
||||
* Implementations SHOULD return the value stored in the "name" key of
|
||||
* the file in the $_FILES array.
|
||||
*
|
||||
* @return string|null The filename sent by the client or null if none
|
||||
* was provided.
|
||||
*/
|
||||
public function getClientFilename()
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the media type sent by the client.
|
||||
*
|
||||
* Do not trust the value returned by this method. A client could send
|
||||
* a malicious media type with the intention to corrupt or hack your
|
||||
* application.
|
||||
*
|
||||
* Implementations SHOULD return the value stored in the "type" key of
|
||||
* the file in the $_FILES array.
|
||||
*
|
||||
* @return string|null The media type sent by the client or null if none
|
||||
* was provided.
|
||||
*/
|
||||
public function getClientMediaType()
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the file size.
|
||||
*
|
||||
* Implementations SHOULD return the value stored in the "size" key of
|
||||
* the file in the $_FILES array if available, as PHP calculates this based
|
||||
* on the actual size transmitted.
|
||||
*
|
||||
* @return int|null The file size in bytes or null if unknown.
|
||||
*/
|
||||
public function getSize()
|
||||
{
|
||||
return $this->size;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,809 @@
|
||||
<?php
|
||||
/**
|
||||
* Slim Framework (http://slimframework.com)
|
||||
*
|
||||
* @link https://github.com/slimphp/Slim
|
||||
* @copyright Copyright (c) 2011-2015 Josh Lockhart
|
||||
* @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
|
||||
*/
|
||||
namespace Slim\Http;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use \Psr\Http\Message\UriInterface;
|
||||
use Slim\Http\Environment;
|
||||
|
||||
/**
|
||||
* Value object representing a URI.
|
||||
*
|
||||
* This interface is meant to represent URIs according to RFC 3986 and to
|
||||
* provide methods for most common operations. Additional functionality for
|
||||
* working with URIs can be provided on top of the interface or externally.
|
||||
* Its primary use is for HTTP requests, but may also be used in other
|
||||
* contexts.
|
||||
*
|
||||
* Instances of this interface are considered immutable; all methods that
|
||||
* might change state MUST be implemented such that they retain the internal
|
||||
* state of the current instance and return an instance that contains the
|
||||
* changed state.
|
||||
*
|
||||
* Typically the Host header will be also be present in the request message.
|
||||
* For server-side requests, the scheme will typically be discoverable in the
|
||||
* server parameters.
|
||||
*
|
||||
* @link http://tools.ietf.org/html/rfc3986 (the URI specification)
|
||||
*/
|
||||
class Uri implements UriInterface
|
||||
{
|
||||
/**
|
||||
* Uri scheme (without "://" suffix)
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $scheme = '';
|
||||
|
||||
/**
|
||||
* Uri user
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $user = '';
|
||||
|
||||
/**
|
||||
* Uri password
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $password = '';
|
||||
|
||||
/**
|
||||
* Uri host
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $host = '';
|
||||
|
||||
/**
|
||||
* Uri port number
|
||||
*
|
||||
* @var null|int
|
||||
*/
|
||||
protected $port;
|
||||
|
||||
/**
|
||||
* Uri base path
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $basePath = '';
|
||||
|
||||
/**
|
||||
* Uri path
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $path = '';
|
||||
|
||||
/**
|
||||
* Uri query string (without "?" prefix)
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $query = '';
|
||||
|
||||
/**
|
||||
* Uri fragment string (without "#" prefix)
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $fragment = '';
|
||||
|
||||
/**
|
||||
* Create new Uri.
|
||||
*
|
||||
* @param string $scheme Uri scheme.
|
||||
* @param string $host Uri host.
|
||||
* @param int $port Uri port number.
|
||||
* @param string $path Uri path.
|
||||
* @param string $query Uri query string.
|
||||
* @param string $fragment Uri fragment.
|
||||
* @param string $user Uri user.
|
||||
* @param string $password Uri password.
|
||||
*/
|
||||
public function __construct($scheme, $host, $port = null, $path = '/', $query = '', $fragment = '', $user = '', $password = '')
|
||||
{
|
||||
$this->scheme = $this->filterScheme($scheme);
|
||||
$this->host = $host;
|
||||
$this->port = $this->filterPort($port);
|
||||
$this->path = empty($path) ? '/' : $this->filterPath($path);
|
||||
$this->query = $this->filterQuery($query);
|
||||
$this->fragment = $this->filterQuery($fragment);
|
||||
$this->user = $user;
|
||||
$this->password = $password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new Uri from string.
|
||||
*
|
||||
* @param string $uri Complete Uri string
|
||||
* (i.e., https://user:pass@host:443/path?query).
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public static function createFromString($uri)
|
||||
{
|
||||
if (!is_string($uri) && !method_exists($uri, '__toString')) {
|
||||
throw new InvalidArgumentException('Uri must be a string');
|
||||
}
|
||||
|
||||
$parts = parse_url($uri);
|
||||
$scheme = isset($parts['scheme']) ? $parts['scheme'] : '';
|
||||
$user = isset($parts['user']) ? $parts['user'] : '';
|
||||
$pass = isset($parts['pass']) ? $parts['pass'] : '';
|
||||
$host = isset($parts['host']) ? $parts['host'] : '';
|
||||
$port = isset($parts['port']) ? $parts['port'] : null;
|
||||
$path = isset($parts['path']) ? $parts['path'] : '';
|
||||
$query = isset($parts['query']) ? $parts['query'] : '';
|
||||
$fragment = isset($parts['fragment']) ? $parts['fragment'] : '';
|
||||
|
||||
return new static($scheme, $host, $port, $path, $query, $fragment, $user, $pass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new Uri from environment.
|
||||
*
|
||||
* @param Environment $env
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public static function createFromEnvironment(Environment $env)
|
||||
{
|
||||
// Scheme
|
||||
$isSecure = $env->get('HTTPS');
|
||||
$scheme = (empty($isSecure) || $isSecure === 'off') ? 'http' : 'https';
|
||||
|
||||
// Authority: Username and password
|
||||
$username = $env->get('PHP_AUTH_USER', '');
|
||||
$password = $env->get('PHP_AUTH_PW', '');
|
||||
|
||||
// Authority: Host
|
||||
if ($env->has('HTTP_HOST')) {
|
||||
$host = $env->get('HTTP_HOST');
|
||||
} else {
|
||||
$host = $env->get('SERVER_NAME');
|
||||
}
|
||||
|
||||
// Authority: Port
|
||||
$port = (int)$env->get('SERVER_PORT', 80);
|
||||
if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $host, $matches)) {
|
||||
$host = $matches[1];
|
||||
|
||||
if ($matches[2]) {
|
||||
$port = (int) substr($matches[2], 1);
|
||||
}
|
||||
} else {
|
||||
$pos = strpos($host, ':');
|
||||
if ($pos !== false) {
|
||||
$port = (int) substr($host, $pos + 1);
|
||||
$host = strstr($host, ':', true);
|
||||
}
|
||||
}
|
||||
|
||||
// Path
|
||||
$requestScriptName = parse_url($env->get('SCRIPT_NAME'), PHP_URL_PATH);
|
||||
$requestScriptDir = dirname($requestScriptName);
|
||||
$requestUri = parse_url($env->get('REQUEST_URI'), PHP_URL_PATH);
|
||||
$basePath = '';
|
||||
$virtualPath = $requestUri;
|
||||
if (stripos($requestUri, $requestScriptName) === 0) {
|
||||
$basePath = $requestScriptName;
|
||||
} elseif ($requestScriptDir !== '/' && stripos($requestUri, $requestScriptDir) === 0) {
|
||||
$basePath = $requestScriptDir;
|
||||
}
|
||||
|
||||
if ($basePath) {
|
||||
$virtualPath = ltrim(substr($requestUri, strlen($basePath)), '/');
|
||||
}
|
||||
|
||||
// Query string
|
||||
$queryString = $env->get('QUERY_STRING', '');
|
||||
|
||||
// Fragment
|
||||
$fragment = '';
|
||||
|
||||
// Build Uri
|
||||
$uri = new static($scheme, $host, $port, $virtualPath, $queryString, $fragment, $username, $password);
|
||||
if ($basePath) {
|
||||
$uri = $uri->withBasePath($basePath);
|
||||
}
|
||||
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/********************************************************************************
|
||||
* Scheme
|
||||
*******************************************************************************/
|
||||
|
||||
/**
|
||||
* Retrieve the scheme component of the URI.
|
||||
*
|
||||
* If no scheme is present, this method MUST return an empty string.
|
||||
*
|
||||
* The value returned MUST be normalized to lowercase, per RFC 3986
|
||||
* Section 3.1.
|
||||
*
|
||||
* The trailing ":" character is not part of the scheme and MUST NOT be
|
||||
* added.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc3986#section-3.1
|
||||
* @return string The URI scheme.
|
||||
*/
|
||||
public function getScheme()
|
||||
{
|
||||
return $this->scheme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified scheme.
|
||||
*
|
||||
* This method MUST retain the state of the current instance, and return
|
||||
* an instance that contains the specified scheme.
|
||||
*
|
||||
* Implementations MUST support the schemes "http" and "https" case
|
||||
* insensitively, and MAY accommodate other schemes if required.
|
||||
*
|
||||
* An empty scheme is equivalent to removing the scheme.
|
||||
*
|
||||
* @param string $scheme The scheme to use with the new instance.
|
||||
* @return self A new instance with the specified scheme.
|
||||
* @throws \InvalidArgumentException for invalid or unsupported schemes.
|
||||
*/
|
||||
public function withScheme($scheme)
|
||||
{
|
||||
$scheme = $this->filterScheme($scheme);
|
||||
$clone = clone $this;
|
||||
$clone->scheme = $scheme;
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Uri scheme.
|
||||
*
|
||||
* @param string $scheme Raw Uri scheme.
|
||||
* @return string
|
||||
*
|
||||
* @throws InvalidArgumentException If the Uri scheme is not a string.
|
||||
* @throws InvalidArgumentException If Uri scheme is not "", "https", or "http".
|
||||
*/
|
||||
protected function filterScheme($scheme)
|
||||
{
|
||||
static $valid = [
|
||||
'' => true,
|
||||
'https' => true,
|
||||
'http' => true,
|
||||
];
|
||||
|
||||
if (!is_string($scheme) && !method_exists($scheme, '__toString')) {
|
||||
throw new InvalidArgumentException('Uri scheme must be a string');
|
||||
}
|
||||
|
||||
$scheme = str_replace('://', '', strtolower((string)$scheme));
|
||||
if (!isset($valid[$scheme])) {
|
||||
throw new InvalidArgumentException('Uri scheme must be one of: "", "https", "http"');
|
||||
}
|
||||
|
||||
return $scheme;
|
||||
}
|
||||
|
||||
/********************************************************************************
|
||||
* Authority
|
||||
*******************************************************************************/
|
||||
|
||||
/**
|
||||
* Retrieve the authority component of the URI.
|
||||
*
|
||||
* If no authority information is present, this method MUST return an empty
|
||||
* string.
|
||||
*
|
||||
* The authority syntax of the URI is:
|
||||
*
|
||||
* <pre>
|
||||
* [user-info@]host[:port]
|
||||
* </pre>
|
||||
*
|
||||
* If the port component is not set or is the standard port for the current
|
||||
* scheme, it SHOULD NOT be included.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc3986#section-3.2
|
||||
* @return string The URI authority, in "[user-info@]host[:port]" format.
|
||||
*/
|
||||
public function getAuthority()
|
||||
{
|
||||
$userInfo = $this->getUserInfo();
|
||||
$host = $this->getHost();
|
||||
$port = $this->getPort();
|
||||
|
||||
return ($userInfo ? $userInfo . '@' : '') . $host . ($port !== null ? ':' . $port : '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the user information component of the URI.
|
||||
*
|
||||
* If no user information is present, this method MUST return an empty
|
||||
* string.
|
||||
*
|
||||
* If a user is present in the URI, this will return that value;
|
||||
* additionally, if the password is also present, it will be appended to the
|
||||
* user value, with a colon (":") separating the values.
|
||||
*
|
||||
* The trailing "@" character is not part of the user information and MUST
|
||||
* NOT be added.
|
||||
*
|
||||
* @return string The URI user information, in "username[:password]" format.
|
||||
*/
|
||||
public function getUserInfo()
|
||||
{
|
||||
return $this->user . ($this->password ? ':' . $this->password : '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified user information.
|
||||
*
|
||||
* This method MUST retain the state of the current instance, and return
|
||||
* an instance that contains the specified user information.
|
||||
*
|
||||
* Password is optional, but the user information MUST include the
|
||||
* user; an empty string for the user is equivalent to removing user
|
||||
* information.
|
||||
*
|
||||
* @param string $user The user name to use for authority.
|
||||
* @param null|string $password The password associated with $user.
|
||||
* @return self A new instance with the specified user information.
|
||||
*/
|
||||
public function withUserInfo($user, $password = null)
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->user = $user;
|
||||
$clone->password = $password ? $password : '';
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the host component of the URI.
|
||||
*
|
||||
* If no host is present, this method MUST return an empty string.
|
||||
*
|
||||
* The value returned MUST be normalized to lowercase, per RFC 3986
|
||||
* Section 3.2.2.
|
||||
*
|
||||
* @see http://tools.ietf.org/html/rfc3986#section-3.2.2
|
||||
* @return string The URI host.
|
||||
*/
|
||||
public function getHost()
|
||||
{
|
||||
return $this->host;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified host.
|
||||
*
|
||||
* This method MUST retain the state of the current instance, and return
|
||||
* an instance that contains the specified host.
|
||||
*
|
||||
* An empty host value is equivalent to removing the host.
|
||||
*
|
||||
* @param string $host The hostname to use with the new instance.
|
||||
* @return self A new instance with the specified host.
|
||||
* @throws \InvalidArgumentException for invalid hostnames.
|
||||
*/
|
||||
public function withHost($host)
|
||||
{
|
||||
$clone = clone $this;
|
||||
$clone->host = $host;
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the port component of the URI.
|
||||
*
|
||||
* If a port is present, and it is non-standard for the current scheme,
|
||||
* this method MUST return it as an integer. If the port is the standard port
|
||||
* used with the current scheme, this method SHOULD return null.
|
||||
*
|
||||
* If no port is present, and no scheme is present, this method MUST return
|
||||
* a null value.
|
||||
*
|
||||
* If no port is present, but a scheme is present, this method MAY return
|
||||
* the standard port for that scheme, but SHOULD return null.
|
||||
*
|
||||
* @return null|int The URI port.
|
||||
*/
|
||||
public function getPort()
|
||||
{
|
||||
return $this->port && !$this->hasStandardPort() ? $this->port : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified port.
|
||||
*
|
||||
* This method MUST retain the state of the current instance, and return
|
||||
* an instance that contains the specified port.
|
||||
*
|
||||
* Implementations MUST raise an exception for ports outside the
|
||||
* established TCP and UDP port ranges.
|
||||
*
|
||||
* A null value provided for the port is equivalent to removing the port
|
||||
* information.
|
||||
*
|
||||
* @param null|int $port The port to use with the new instance; a null value
|
||||
* removes the port information.
|
||||
* @return self A new instance with the specified port.
|
||||
* @throws \InvalidArgumentException for invalid ports.
|
||||
*/
|
||||
public function withPort($port)
|
||||
{
|
||||
$port = $this->filterPort($port);
|
||||
$clone = clone $this;
|
||||
$clone->port = $port;
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this Uri use a standard port?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function hasStandardPort()
|
||||
{
|
||||
return ($this->scheme === 'http' && $this->port === 80) || ($this->scheme === 'https' && $this->port === 443);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Uri port.
|
||||
*
|
||||
* @param null|int $port The Uri port number.
|
||||
* @return null|int
|
||||
*
|
||||
* @throws InvalidArgumentException If the port is invalid.
|
||||
*/
|
||||
protected function filterPort($port)
|
||||
{
|
||||
if (is_null($port) || (is_integer($port) && ($port >= 1 && $port <= 65535))) {
|
||||
return $port;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Uri port must be null or an integer between 1 and 65535 (inclusive)');
|
||||
}
|
||||
|
||||
/********************************************************************************
|
||||
* Path
|
||||
*******************************************************************************/
|
||||
|
||||
/**
|
||||
* Retrieve the path component of the URI.
|
||||
*
|
||||
* The path can either be empty or absolute (starting with a slash) or
|
||||
* rootless (not starting with a slash). Implementations MUST support all
|
||||
* three syntaxes.
|
||||
*
|
||||
* Normally, the empty path "" and absolute path "/" are considered equal as
|
||||
* defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically
|
||||
* do this normalization because in contexts with a trimmed base path, e.g.
|
||||
* the front controller, this difference becomes significant. It's the task
|
||||
* of the user to handle both "" and "/".
|
||||
*
|
||||
* The value returned MUST be percent-encoded, but MUST NOT double-encode
|
||||
* any characters. To determine what characters to encode, please refer to
|
||||
* RFC 3986, Sections 2 and 3.3.
|
||||
*
|
||||
* As an example, if the value should include a slash ("/") not intended as
|
||||
* delimiter between path segments, that value MUST be passed in encoded
|
||||
* form (e.g., "%2F") to the instance.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc3986#section-2
|
||||
* @see https://tools.ietf.org/html/rfc3986#section-3.3
|
||||
* @return string The URI path.
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
return $this->path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified path.
|
||||
*
|
||||
* This method MUST retain the state of the current instance, and return
|
||||
* an instance that contains the specified path.
|
||||
*
|
||||
* The path can either be empty or absolute (starting with a slash) or
|
||||
* rootless (not starting with a slash). Implementations MUST support all
|
||||
* three syntaxes.
|
||||
*
|
||||
* If the path is intended to be domain-relative rather than path relative then
|
||||
* it must begin with a slash ("/"). Paths not starting with a slash ("/")
|
||||
* are assumed to be relative to some base path known to the application or
|
||||
* consumer.
|
||||
*
|
||||
* Users can provide both encoded and decoded path characters.
|
||||
* Implementations ensure the correct encoding as outlined in getPath().
|
||||
*
|
||||
* @param string $path The path to use with the new instance.
|
||||
* @return self A new instance with the specified path.
|
||||
* @throws \InvalidArgumentException for invalid paths.
|
||||
*/
|
||||
public function withPath($path)
|
||||
{
|
||||
if (!is_string($path)) {
|
||||
throw new InvalidArgumentException('Uri path must be a string');
|
||||
}
|
||||
|
||||
$clone = clone $this;
|
||||
$clone->path = $this->filterPath($path);
|
||||
|
||||
// if the path is absolute, then clear basePath
|
||||
if (substr($path, 0, 1) == '/') {
|
||||
$clone->basePath = '';
|
||||
}
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the base path segment of the URI.
|
||||
*
|
||||
* Note: This method is not part of the PSR-7 standard.
|
||||
*
|
||||
* This method MUST return a string; if no path is present it MUST return
|
||||
* an empty string.
|
||||
*
|
||||
* @return string The base path segment of the URI.
|
||||
*/
|
||||
public function getBasePath()
|
||||
{
|
||||
return $this->basePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set base path.
|
||||
*
|
||||
* Note: This method is not part of the PSR-7 standard.
|
||||
*
|
||||
* @param string $basePath
|
||||
* @return self
|
||||
*/
|
||||
public function withBasePath($basePath)
|
||||
{
|
||||
if (!is_string($basePath)) {
|
||||
throw new InvalidArgumentException('Uri path must be a string');
|
||||
}
|
||||
if (!empty($basePath)) {
|
||||
$basePath = '/' . trim($basePath, '/'); // <-- Trim on both sides
|
||||
}
|
||||
$clone = clone $this;
|
||||
|
||||
if ($basePath !== '/') {
|
||||
$clone->basePath = $this->filterPath($basePath);
|
||||
}
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter Uri path.
|
||||
*
|
||||
* This method percent-encodes all reserved
|
||||
* characters in the provided path string. This method
|
||||
* will NOT double-encode characters that are already
|
||||
* percent-encoded.
|
||||
*
|
||||
* @param string $path The raw uri path.
|
||||
* @return string The RFC 3986 percent-encoded uri path.
|
||||
* @link http://www.faqs.org/rfcs/rfc3986.html
|
||||
*/
|
||||
protected function filterPath($path)
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/(?:[^a-zA-Z0-9_\-\.~:@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/',
|
||||
function ($match) {
|
||||
return rawurlencode($match[0]);
|
||||
},
|
||||
$path
|
||||
);
|
||||
}
|
||||
|
||||
/********************************************************************************
|
||||
* Query
|
||||
*******************************************************************************/
|
||||
|
||||
/**
|
||||
* Retrieve the query string of the URI.
|
||||
*
|
||||
* If no query string is present, this method MUST return an empty string.
|
||||
*
|
||||
* The leading "?" character is not part of the query and MUST NOT be
|
||||
* added.
|
||||
*
|
||||
* The value returned MUST be percent-encoded, but MUST NOT double-encode
|
||||
* any characters. To determine what characters to encode, please refer to
|
||||
* RFC 3986, Sections 2 and 3.4.
|
||||
*
|
||||
* As an example, if a value in a key/value pair of the query string should
|
||||
* include an ampersand ("&") not intended as a delimiter between values,
|
||||
* that value MUST be passed in encoded form (e.g., "%26") to the instance.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc3986#section-2
|
||||
* @see https://tools.ietf.org/html/rfc3986#section-3.4
|
||||
* @return string The URI query string.
|
||||
*/
|
||||
public function getQuery()
|
||||
{
|
||||
return $this->query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified query string.
|
||||
*
|
||||
* This method MUST retain the state of the current instance, and return
|
||||
* an instance that contains the specified query string.
|
||||
*
|
||||
* Users can provide both encoded and decoded query characters.
|
||||
* Implementations ensure the correct encoding as outlined in getQuery().
|
||||
*
|
||||
* An empty query string value is equivalent to removing the query string.
|
||||
*
|
||||
* @param string $query The query string to use with the new instance.
|
||||
* @return self A new instance with the specified query string.
|
||||
* @throws \InvalidArgumentException for invalid query strings.
|
||||
*/
|
||||
public function withQuery($query)
|
||||
{
|
||||
if (!is_string($query) && !method_exists($query, '__toString')) {
|
||||
throw new InvalidArgumentException('Uri query must be a string');
|
||||
}
|
||||
$query = ltrim((string)$query, '?');
|
||||
$clone = clone $this;
|
||||
$clone->query = $this->filterQuery($query);
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the query string or fragment of a URI.
|
||||
*
|
||||
* @param string $query The raw uri query string.
|
||||
* @return string The percent-encoded query string.
|
||||
*/
|
||||
protected function filterQuery($query)
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/',
|
||||
function ($match) {
|
||||
return rawurlencode($match[0]);
|
||||
},
|
||||
$query
|
||||
);
|
||||
}
|
||||
|
||||
/********************************************************************************
|
||||
* Fragment
|
||||
*******************************************************************************/
|
||||
|
||||
/**
|
||||
* Retrieve the fragment component of the URI.
|
||||
*
|
||||
* If no fragment is present, this method MUST return an empty string.
|
||||
*
|
||||
* The leading "#" character is not part of the fragment and MUST NOT be
|
||||
* added.
|
||||
*
|
||||
* The value returned MUST be percent-encoded, but MUST NOT double-encode
|
||||
* any characters. To determine what characters to encode, please refer to
|
||||
* RFC 3986, Sections 2 and 3.5.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc3986#section-2
|
||||
* @see https://tools.ietf.org/html/rfc3986#section-3.5
|
||||
* @return string The URI fragment.
|
||||
*/
|
||||
public function getFragment()
|
||||
{
|
||||
return $this->fragment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an instance with the specified URI fragment.
|
||||
*
|
||||
* This method MUST retain the state of the current instance, and return
|
||||
* an instance that contains the specified URI fragment.
|
||||
*
|
||||
* Users can provide both encoded and decoded fragment characters.
|
||||
* Implementations ensure the correct encoding as outlined in getFragment().
|
||||
*
|
||||
* An empty fragment value is equivalent to removing the fragment.
|
||||
*
|
||||
* @param string $fragment The fragment to use with the new instance.
|
||||
* @return self A new instance with the specified fragment.
|
||||
*/
|
||||
public function withFragment($fragment)
|
||||
{
|
||||
if (!is_string($fragment) && !method_exists($fragment, '__toString')) {
|
||||
throw new InvalidArgumentException('Uri fragment must be a string');
|
||||
}
|
||||
$fragment = ltrim((string)$fragment, '#');
|
||||
$clone = clone $this;
|
||||
$clone->fragment = $this->filterQuery($fragment);
|
||||
|
||||
return $clone;
|
||||
}
|
||||
|
||||
/********************************************************************************
|
||||
* Helpers
|
||||
*******************************************************************************/
|
||||
|
||||
/**
|
||||
* Return the string representation as a URI reference.
|
||||
*
|
||||
* Depending on which components of the URI are present, the resulting
|
||||
* string is either a full URI or relative reference according to RFC 3986,
|
||||
* Section 4.1. The method concatenates the various components of the URI,
|
||||
* using the appropriate delimiters:
|
||||
*
|
||||
* - If a scheme is present, it MUST be suffixed by ":".
|
||||
* - If an authority is present, it MUST be prefixed by "//".
|
||||
* - The path can be concatenated without delimiters. But there are two
|
||||
* cases where the path has to be adjusted to make the URI reference
|
||||
* valid as PHP does not allow to throw an exception in __toString():
|
||||
* - If the path is rootless and an authority is present, the path MUST
|
||||
* be prefixed by "/".
|
||||
* - If the path is starting with more than one "/" and no authority is
|
||||
* present, the starting slashes MUST be reduced to one.
|
||||
* - If a query is present, it MUST be prefixed by "?".
|
||||
* - If a fragment is present, it MUST be prefixed by "#".
|
||||
*
|
||||
* @see http://tools.ietf.org/html/rfc3986#section-4.1
|
||||
* @return string
|
||||
*/
|
||||
public function __toString()
|
||||
{
|
||||
$scheme = $this->getScheme();
|
||||
$authority = $this->getAuthority();
|
||||
$basePath = $this->getBasePath();
|
||||
$path = $this->getPath();
|
||||
$query = $this->getQuery();
|
||||
$fragment = $this->getFragment();
|
||||
|
||||
$path = $basePath . '/' . ltrim($path, '/');
|
||||
|
||||
return ($scheme ? $scheme . ':' : '')
|
||||
. ($authority ? '//' . $authority : '')
|
||||
. $path
|
||||
. ($query ? '?' . $query : '')
|
||||
. ($fragment ? '#' . $fragment : '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the fully qualified base URL.
|
||||
*
|
||||
* Note that this method never includes a trailing /
|
||||
*
|
||||
* This method is not part of PSR-7.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getBaseUrl()
|
||||
{
|
||||
$scheme = $this->getScheme();
|
||||
$authority = $this->getAuthority();
|
||||
$basePath = $this->getBasePath();
|
||||
|
||||
if ($authority && substr($basePath, 0, 1) !== '/') {
|
||||
$basePath = $basePath . '/' . $basePath;
|
||||
}
|
||||
|
||||
return ($scheme ? $scheme . ':' : '')
|
||||
. ($authority ? '//' . $authority : '')
|
||||
. rtrim($basePath, '/');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user