/**
  * Open pre-mocked StreamInterface by it's unique uri.
  *
  * @param string $path
  * @param int    $mode
  * @param int    $options
  * @param string &$opened_path
  * @return bool
  */
 public function stream_open($path, $mode, $options, &$opened_path)
 {
     if (!isset(self::$uris[$path])) {
         return false;
     }
     $this->stream = self::$uris[$path];
     $this->mode = $mode;
     $this->stream->rewind();
     return true;
 }
 /**
  * {@inheritdoc}
  */
 public function __toString() : string
 {
     $str = $this->getStartLine();
     foreach ($this->getHeaders() as $name => $values) {
         $str .= sprintf("%s: %s\r\n", $name, implode(', ', $values));
     }
     $str .= "\r\n";
     $this->body->rewind();
     $str .= $this->body->getContents();
     return $str;
 }
Example #3
0
 /**
  * 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 (!is_string($targetPath) || empty($targetPath)) {
         throw new \InvalidArgumentException('Invalid path while moving an uploaded file.', 1436717307);
     }
     if ($this->moved) {
         throw new \RuntimeException('Cannot move uploaded file, as it was already moved.', 1436717308);
     }
     // Check if the target path is inside the allowed paths of TYPO3, and make it absolute.
     $targetPath = GeneralUtility::getFileAbsFileName($targetPath);
     if (empty($targetPath)) {
         throw new \RuntimeException('Cannot move uploaded file, as it was already moved.', 1436717309);
     }
     if (!empty($this->file) && is_uploaded_file($this->file)) {
         if (GeneralUtility::upload_copy_move($this->file, $targetPath . basename($this->file)) === false) {
             throw new \RuntimeException('An error occurred while moving uploaded file', 1436717310);
         }
     } elseif ($this->stream) {
         $handle = fopen($targetPath, 'wb+');
         if ($handle === false) {
             throw new \RuntimeException('Unable to write to target path.', 1436717311);
         }
         $this->stream->rewind();
         while (!$this->stream->eof()) {
             fwrite($handle, $this->stream->read(4096));
         }
         fclose($handle);
     }
     $this->moved = true;
 }
Example #4
0
 /**
  * Copy stream to another stream.
  *
  * @param   StreamInterface  $src   Source stream.
  * @param   StreamInterface  $dest  Target stream.
  *
  * @return  void
  */
 public static function copy(StreamInterface $src, StreamInterface $dest)
 {
     if ($src->isSeekable()) {
         $src->rewind();
     }
     while (!$src->eof()) {
         $dest->write($src->read(4096));
     }
 }
Example #5
0
 public function moveTo($targetPath)
 {
     if (!PHP_SAPI || PHP_SAPI == 'cli') {
         $handle = fopen($targetPath, Stream::MODE_READ_REPLACE);
         if ($handle === false) {
             throw new \RuntimeException('Unable to write to: ' . $targetPath);
         }
         $this->stream->rewind();
         while (!$this->stream->eof()) {
             fwrite($handle, $this->stream->read(4096));
         }
         fclose($handle);
     } else {
         if (move_uploaded_file($this->filePath, $targetPath) === false) {
             throw new \RuntimeException('Error moving uploaded file');
         }
     }
 }
Example #6
0
 /**
  * @param StreamInterface $stream
  */
 protected function body($stream)
 {
     if ($stream instanceof Messages\Stream\Implementation) {
         $stream->rewind();
         $this->fpassthru($stream->resource());
     } else {
         $this->output((string) $stream);
     }
 }
 /**
  * Parse a response from a stream.
  *
  * @param StreamInterface $stream
  * @return ResponseInterface
  * @throws InvalidArgumentException when the stream is not readable.
  * @throws UnexpectedValueException when errors occur parsing the message.
  */
 public static function fromStream(StreamInterface $stream)
 {
     if (!$stream->isReadable() || !$stream->isSeekable()) {
         throw new InvalidArgumentException('Message stream must be both readable and seekable');
     }
     $stream->rewind();
     list($version, $status, $reasonPhrase) = self::getStatusLine($stream);
     list($headers, $body) = self::splitStream($stream);
     return (new Response($body, $status, $headers))->withProtocolVersion($version)->withStatus((int) $status, $reasonPhrase);
 }
Example #8
0
 public function testReadAndWrite()
 {
     $this->assertEquals(0, $this->stream->getSize());
     $this->stream->write("Hello World, And All Developers!");
     $this->assertEquals(32, $this->stream->getSize());
     // size
     $this->assertEquals(32, $this->stream->tell());
     // pointer
     $this->stream->rewind();
     $this->assertEquals(0, $this->stream->tell());
     $this->assertFalse($this->stream->eof());
     $this->assertEquals("Hell", $this->stream->read(4));
     $this->assertEquals("o World, ", $this->stream->read(9));
     $this->assertEquals("And All Developers!", $this->stream->getContents());
     $this->assertTrue($this->stream->eof());
     $this->stream->seek(12);
     $this->assertEquals(6, $this->stream->write('Hum...'));
     $this->assertEquals("ll Developers!", $this->stream->getContents());
     $this->assertEquals("Hello World,Hum...ll Developers!", $this->stream->__toString());
 }
 /**
  * Deserialize a request stream to a request instance.
  *
  * @param StreamInterface $stream
  * @return Request
  * @throws UnexpectedValueException when errors occur parsing the message.
  */
 public static function fromStream(StreamInterface $stream)
 {
     if (!$stream->isReadable() || !$stream->isSeekable()) {
         throw new InvalidArgumentException('Message stream must be both readable and seekable');
     }
     $stream->rewind();
     list($method, $requestTarget, $version) = self::getRequestLine($stream);
     $uri = self::createUriFromRequestTarget($requestTarget);
     list($headers, $body) = self::splitStream($stream);
     return (new Request($uri, $method, $body, $headers))->withProtocolVersion($version)->withRequestTarget($requestTarget);
 }
 /**
  * Write internal stream to given path
  *
  * @param string $path
  */
 protected function writeFile($path)
 {
     $handle = fopen($path, Stream::MODE_READ_WRITE_RESET);
     if ($handle === false) {
         throw new \RuntimeException('Unable to write to path: ' . $path);
     }
     $this->stream->rewind();
     while (!$this->stream->eof()) {
         fwrite($handle, $this->stream->read(4096));
     }
     fclose($handle);
 }
Example #11
0
 /**
  * Write internal stream to given path
  *
  * @param string $path
  */
 private function writeFile($path)
 {
     $handle = fopen($path, 'wb+');
     if (false === $handle) {
         throw new RuntimeException('Unable to write to designated path');
     }
     $this->stream->rewind();
     while (!$this->stream->eof()) {
         fwrite($handle, $this->stream->read(4096));
     }
     fclose($handle);
 }
 /**
  * Write the stream to the given path.
  *
  * @param StreamInterface $stream
  * @param string          $path
  */
 protected static function writeStream(StreamInterface $stream, $path)
 {
     $dir = dirname($path);
     if (!is_dir($dir)) {
         mkdir($dir, 0777, true);
     }
     $handle = fopen($path, 'wb+');
     if (false === $handle) {
         throw new RuntimeException('Unable to write to designated path');
     }
     $stream->rewind();
     while (!$stream->eof()) {
         fwrite($handle, $stream->read(4096));
     }
     fclose($handle);
 }
Example #13
0
 /**
  * Creates a stream.
  *
  * @param null|resource|string|\Psr\Http\Message\StreamInterface|null $body The body
  *
  * @return \Psr\Http\Message\StreamInterface The stream
  */
 private function doCreateStream($body)
 {
     if ($body instanceof StreamInterface) {
         $body->rewind();
         return $body;
     }
     if (is_resource($body)) {
         return $this->doCreateStream(new Stream($body));
     }
     $stream = new Stream('php://memory', 'rw');
     if ($body === null) {
         return $stream;
     }
     $stream->write((string) $body);
     return $this->doCreateStream($stream);
 }
 /**
  * Write a response to the connection as FCGI_STDOUT records.
  *
  * @param int             $requestId  The request id to write to
  * @param string          $headerData The header data to write (including terminating CRLFCRLF)
  * @param StreamInterface $stream     The stream to write
  */
 private function writeResponse($requestId, $headerData, StreamInterface $stream)
 {
     $data = $headerData;
     $eof = false;
     $stream->rewind();
     do {
         $dataLength = strlen($data);
         if ($dataLength < 65535 && !$eof && !($eof = $stream->eof())) {
             $readLength = 65535 - $dataLength;
             $data .= $stream->read($readLength);
             $dataLength = strlen($data);
         }
         $writeSize = min($dataLength, 65535);
         $writeData = substr($data, 0, $writeSize);
         $data = substr($data, $writeSize);
         $this->writeRecord($requestId, DaemonInterface::FCGI_STDOUT, $writeData);
     } while ($writeSize === 65535);
     $this->writeRecord($requestId, DaemonInterface::FCGI_STDOUT);
 }
Example #15
0
 private function outputBody(StreamInterface $body)
 {
     if ($this->chunkSize > 0) {
         if ($body->isSeekable()) {
             $body->rewind();
         }
         while (!$body->eof()) {
             print $body->read($this->chunkSize);
         }
     } else {
         print (string) $body;
     }
 }
Example #16
0
 /**
  * Parses csv.
  * 
  * @param StreamInterface $body
  * 
  * @return array
  */
 protected function parseCsv(StreamInterface $body)
 {
     if ($body->isSeekable()) {
         $body->rewind();
     }
     $stream = $body->detach();
     $data = [];
     while (($row = fgetcsv($stream)) !== false) {
         $data[] = $row;
     }
     fclose($stream);
     return $data;
 }
Example #17
0
 /**
  * addFile_from_Psr7Stream
  * 
  * dds an open stream to the archive uncompressed
  *
  * @param String $name - path of file in archive (including directory).
  * @param Resource $stream - contents of file as a stream resource
  * @param array $opt - Hash of options for file (optional, see "File Options" below).
  * 
  * File Options:
  *  time     - Last-modified timestamp (seconds since the epoch) of
  *             this file.  Defaults to the current time.
  *  comment  - Comment related to this file.
  *
  * Examples:
  *
  *   // create a temporary file stream and write text to it
  *   $fp = tmpfile();
  *   fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
  *
  *   // add a file named 'streamfile.txt' from the content of the stream
  *   $x->addFile_from_stream('streamfile.txt', $fp);
  *
  * @return void
  */
 public function addFileFromPsr7Stream($name, \Psr\Http\Message\StreamInterface $stream, $opt = array())
 {
     $name = $this->filterFilename($name);
     $block_size = 1048576;
     // process in 1 megabyte chunks
     $algo = 'crc32b';
     $meth = static::METHOD_STORE;
     // calculate header attributes
     $stream->seek(0, SEEK_END);
     $zlen = $len = $stream->tell();
     // send file header
     $hlen = $this->addFileHeader($name, $opt, $meth);
     // Stream data and calculate CRC32
     $stream->rewind();
     $hash_ctx = hash_init($algo);
     while (!$stream->eof()) {
         $data = $stream->read($block_size);
         hash_update($hash_ctx, $data);
         // send data
         $this->send($data);
     }
     $crc = hexdec(hash_final($hash_ctx));
     // send file footer + CDR record
     $this->addFileFooter($name, $opt, $meth, $crc, $zlen, $len, $hlen);
 }
Example #18
0
 /**
  * @param StreamInterface $stream
  *
  * @return string
  */
 protected function streamToString(StreamInterface $stream)
 {
     $stream->rewind();
     return $stream->getContents();
 }
Example #19
0
 /**
  * Parse path to XML document/string content.
  *
  * @param resource $parser Parser.
  * @param StreamInterface $stream XML document stream.
  * @return AbstractSaxHandler $this Fluent interface.
  *
  * @throws \RuntimeException
  */
 private function process($parser, StreamInterface $stream)
 {
     if ($stream->eof()) {
         $stream->rewind();
     }
     while ($data = $stream->read($this->options['buffer_size'])) {
         xml_parse($parser, $data, $stream->eof()) || $this->onParseError(xml_error_string(xml_get_error_code($parser)), xml_get_error_code($parser), xml_get_current_line_number($parser));
     }
     return $this;
 }
Example #20
0
 /**
  * Sends Body.
  *
  * @param Psr\Http\Message\StreamInterface $body The body to send as stream
  *
  * @author Benjamin Carl <*****@*****.**>
  * @return void
  * @access protected
  */
 protected function sendBody(Stream $body)
 {
     // I don't trust that this will be at the beginning of the stream, so reset.
     $body->rewind();
     // writing to an arbitrary stream.
     // @todo Use stream operations to make this more robust and allow
     $bytes = 0;
     if ($bytes = $body->getSize() && $bytes < 500) {
         print $body->getContents();
     } else {
         while (!$body->eof()) {
             $data = $body->read(1024);
             print $data;
         }
     }
 }
 public function rewind()
 {
     return $this->stream->rewind();
 }
Example #22
0
 /**
  * Transform a React Response to a valid PSR7 ResponseInterface instance.
  *
  * @param ReactResponse   $response
  * @param StreamInterface $body
  *
  * @return ResponseInterface
  */
 private function buildResponse(ReactResponse $response, StreamInterface $body)
 {
     $body->rewind();
     return $this->responseFactory->createResponse($response->getCode(), $response->getReasonPhrase(), $response->getHeaders(), $body, $response->getVersion());
 }
Example #23
0
/**
 * Calculate a hash of a Stream
 *
 * @param StreamInterface $stream    Stream to calculate the hash for
 * @param string          $algo      Hash algorithm (e.g. md5, crc32, etc)
 * @param bool            $rawOutput Whether or not to use raw output
 *
 * @return string Returns the hash of the stream
 * @throws \RuntimeException on error.
 */
function hash(StreamInterface $stream, $algo, $rawOutput = false)
{
    $pos = $stream->tell();
    if ($pos > 0) {
        $stream->rewind();
    }
    $ctx = hash_init($algo);
    while (!$stream->eof()) {
        hash_update($ctx, $stream->read(1048576));
    }
    $out = hash_final($ctx, (bool) $rawOutput);
    $stream->seek($pos);
    return $out;
}
Example #24
0
 /**
  * {@inheritdoc}
  */
 public function rewind()
 {
     $this->stream->rewind();
 }