Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 237 lines (205 sloc) 6.851 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
<?php

namespace Guzzle\Http;

use Guzzle\Common\Stream;
use Guzzle\Common\Exception\InvalidArgumentException;

/**
* Entity body used with an HTTP request or response
*/
class EntityBody extends Stream
{
    /**
* @var bool Content-Encoding of the entity body if known
*/
    protected $contentEncoding = false;

    /**
* Create a new EntityBody based on the input type
*
* @param resource|string|EntityBody $resource Entity body data
* @param int $size Size of the data contained in the resource
*
* @return EntityBody
* @throws InvalidArgumentException if the $resource arg is not a resource or string
*/
    public static function factory($resource = '', $size = null)
    {
        if ($resource instanceof self) {
            return $resource;
        }

        switch (gettype($resource)) {
            case 'string':
                return self::fromString($resource);
            case 'resource':
                return new static($resource, $size);
            case 'object':
                if (method_exists($resource, '__toString')) {
                    return self::fromString((string) $resource);
                }
                break;
            case 'array':
                return self::fromString(http_build_query($resource));
        }

        throw new InvalidArgumentException('Invalid resource type');
    }

    /**
* Create a new EntityBody from a string
*
* @param string $string String of data
*
* @return EntityBody
*/
    public static function fromString($string)
    {
        $stream = fopen('php://temp', 'r+');
        fwrite($stream, $string);
        rewind($stream);

        return new static($stream);
    }

    /**
* If the stream is readable, compress the data in the stream using deflate
* compression. The uncompressed stream is then closed, and the compressed
* stream then becomes the wrapped stream.
*
* @param string $filter Compression filter
*
* @return bool Returns TRUE on success or FALSE on failure
*/
    public function compress($filter = 'zlib.deflate')
    {
        $result = $this->handleCompression($filter);
        $this->contentEncoding = $result ? $filter : false;

        return $result;
    }

    /**
* Uncompress a deflated string. Once uncompressed, the uncompressed
* string is then used as the wrapped stream.
*
* @param string $filter De-compression filter
*
* @return bool Returns TRUE on success or FALSE on failure
*/
    public function uncompress($filter = 'zlib.inflate')
    {
        $offsetStart = 0;

        // When inflating gzipped data, the first 10 bytes must be stripped
        // if a gzip header is present
        if ($filter == 'zlib.inflate') {
            // @codeCoverageIgnoreStart
            if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
                return false;
            }
            // @codeCoverageIgnoreEnd
            $this->seek(0);
            if (fread($this->stream, 3) == "\x1f\x8b\x08") {
                $offsetStart = 10;
            }
        }

        $this->contentEncoding = false;

        return $this->handleCompression($filter, $offsetStart);
    }

    /**
* Get the Content-Length of the entity body if possible (alias of getSize)
*
* @return int|false
*/
    public function getContentLength()
    {
        return $this->getSize();
    }

    /**
* Guess the Content-Type or return the default application/octet-stream
*
* @return string
* @see http://www.php.net/manual/en/function.finfo-open.php
*/
    public function getContentType()
    {
        if (!class_exists('finfo', false) || !($this->isLocal() && $this->getWrapper() == 'plainfile' && file_exists($this->getUri()))) {
            return 'application/octet-stream';
        }

        $finfo = new \finfo(FILEINFO_MIME_TYPE);

        return $finfo->file($this->getUri());
    }

    /**
* Get an MD5 checksum of the stream's contents
*
* @param bool $rawOutput Whether or not to use raw output
* @param bool $base64Encode Whether or not to base64 encode raw output
* (only if raw output is true)
*
* @return bool|string Returns an MD5 string on success or FALSE on failure
*/
    public function getContentMd5($rawOutput = false, $base64Encode = false)
    {
        if (!$this->seek(0)) {
            return false;
        }

        $ctx = hash_init('md5');
        while ($data = $this->read(1024)) {
            hash_update($ctx, $data);
        }

        $out = hash_final($ctx, (bool) $rawOutput);
        $this->seek(0);

        return ((bool) $base64Encode && (bool) $rawOutput) ? base64_encode($out) : $out;
    }

    /**
* Set the type of encoding stream that was used on the entity body
*
* @param string $streamFilterContentEncoding Stream filter used
*
* @return EntityBody
*/
    public function setStreamFilterContentEncoding($streamFilterContentEncoding)
    {
        $this->contentEncoding = $streamFilterContentEncoding;

        return $this;
    }

    /**
* Get the Content-Encoding of the EntityBody
*
* @return bool|string
*/
    public function getContentEncoding()
    {
        return strtr($this->contentEncoding, array(
            'zlib.deflate' => 'gzip',
            'bzip2.compress' => 'compress'
        )) ?: false;
    }

    /**
* Handles compression or uncompression of stream data
*
* @param string $filter Name of the filter to use (zlib.deflate or zlib.inflate)
* @param int $offsetStart Number of bytes to skip from start
*
* @return bool Returns TRUE on success or FALSE on failure
*/
    protected function handleCompression($filter, $offsetStart = null)
    {
        // @codeCoverageIgnoreStart
        if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
            return false;
        }
        // @codeCoverageIgnoreEnd

        $handle = fopen('php://temp', 'r+');
        $filter = @stream_filter_append($handle, $filter, STREAM_FILTER_WRITE);
        if (!$filter) {
            return false;
        }

        // Seek to the beginning of the stream if possible
        $this->seek(0);

        if ($offsetStart) {
            fread($this->stream, $offsetStart);
        }

        while ($data = fread($this->stream, 8096)) {
            fwrite($handle, $data);
        }

        fclose($this->stream);
        $this->stream = $handle;
        stream_filter_remove($filter);
        $stat = fstat($this->stream);
        $this->size = $stat['size'];
        $this->rebuildCache();
        $this->seek(0);

        return true;
    }
}
Something went wrong with that request. Please try again.