EntityBody.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. <?php
  2. namespace Guzzle\Http;
  3. use Guzzle\Common\Version;
  4. use Guzzle\Stream\Stream;
  5. use Guzzle\Common\Exception\InvalidArgumentException;
  6. use Guzzle\Http\Mimetypes;
  7. /**
  8. * Entity body used with an HTTP request or response
  9. */
  10. class EntityBody extends Stream implements EntityBodyInterface
  11. {
  12. /** @var bool Content-Encoding of the entity body if known */
  13. protected $contentEncoding = false;
  14. /** @var callable Method to invoke for rewinding a stream */
  15. protected $rewindFunction;
  16. /**
  17. * Create a new EntityBody based on the input type
  18. *
  19. * @param resource|string|EntityBody $resource Entity body data
  20. * @param int $size Size of the data contained in the resource
  21. *
  22. * @return EntityBody
  23. * @throws InvalidArgumentException if the $resource arg is not a resource or string
  24. */
  25. public static function factory($resource = '', $size = null)
  26. {
  27. if ($resource instanceof EntityBodyInterface) {
  28. return $resource;
  29. }
  30. switch (gettype($resource)) {
  31. case 'string':
  32. return self::fromString($resource);
  33. case 'resource':
  34. return new static($resource, $size);
  35. case 'object':
  36. if (method_exists($resource, '__toString')) {
  37. return self::fromString((string) $resource);
  38. }
  39. break;
  40. case 'array':
  41. return self::fromString(http_build_query($resource));
  42. }
  43. throw new InvalidArgumentException('Invalid resource type');
  44. }
  45. public function setRewindFunction($callable)
  46. {
  47. if (!is_callable($callable)) {
  48. throw new InvalidArgumentException('Must specify a callable');
  49. }
  50. $this->rewindFunction = $callable;
  51. return $this;
  52. }
  53. public function rewind()
  54. {
  55. return $this->rewindFunction ? call_user_func($this->rewindFunction, $this) : parent::rewind();
  56. }
  57. /**
  58. * Create a new EntityBody from a string
  59. *
  60. * @param string $string String of data
  61. *
  62. * @return EntityBody
  63. */
  64. public static function fromString($string)
  65. {
  66. $stream = fopen('php://temp', 'r+');
  67. if ($string !== '') {
  68. fwrite($stream, $string);
  69. rewind($stream);
  70. }
  71. return new static($stream);
  72. }
  73. public function compress($filter = 'zlib.deflate')
  74. {
  75. $result = $this->handleCompression($filter);
  76. $this->contentEncoding = $result ? $filter : false;
  77. return $result;
  78. }
  79. public function uncompress($filter = 'zlib.inflate')
  80. {
  81. $offsetStart = 0;
  82. // When inflating gzipped data, the first 10 bytes must be stripped
  83. // if a gzip header is present
  84. if ($filter == 'zlib.inflate') {
  85. // @codeCoverageIgnoreStart
  86. if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
  87. return false;
  88. }
  89. // @codeCoverageIgnoreEnd
  90. if (stream_get_contents($this->stream, 3, 0) === "\x1f\x8b\x08") {
  91. $offsetStart = 10;
  92. }
  93. }
  94. $this->contentEncoding = false;
  95. return $this->handleCompression($filter, $offsetStart);
  96. }
  97. public function getContentLength()
  98. {
  99. return $this->getSize();
  100. }
  101. public function getContentType()
  102. {
  103. return $this->getUri() ? Mimetypes::getInstance()->fromFilename($this->getUri()) : null;
  104. }
  105. public function getContentMd5($rawOutput = false, $base64Encode = false)
  106. {
  107. if ($hash = self::getHash($this, 'md5', $rawOutput)) {
  108. return $hash && $base64Encode ? base64_encode($hash) : $hash;
  109. } else {
  110. return false;
  111. }
  112. }
  113. /**
  114. * Calculate the MD5 hash of an entity body
  115. *
  116. * @param EntityBodyInterface $body Entity body to calculate the hash for
  117. * @param bool $rawOutput Whether or not to use raw output
  118. * @param bool $base64Encode Whether or not to base64 encode raw output (only if raw output is true)
  119. *
  120. * @return bool|string Returns an MD5 string on success or FALSE on failure
  121. * @deprecated This will be deprecated soon
  122. * @codeCoverageIgnore
  123. */
  124. public static function calculateMd5(EntityBodyInterface $body, $rawOutput = false, $base64Encode = false)
  125. {
  126. Version::warn(__CLASS__ . ' is deprecated. Use getContentMd5()');
  127. return $body->getContentMd5($rawOutput, $base64Encode);
  128. }
  129. public function setStreamFilterContentEncoding($streamFilterContentEncoding)
  130. {
  131. $this->contentEncoding = $streamFilterContentEncoding;
  132. return $this;
  133. }
  134. public function getContentEncoding()
  135. {
  136. return strtr($this->contentEncoding, array(
  137. 'zlib.deflate' => 'gzip',
  138. 'bzip2.compress' => 'compress'
  139. )) ?: false;
  140. }
  141. protected function handleCompression($filter, $offsetStart = 0)
  142. {
  143. // @codeCoverageIgnoreStart
  144. if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
  145. return false;
  146. }
  147. // @codeCoverageIgnoreEnd
  148. $handle = fopen('php://temp', 'r+');
  149. $filter = @stream_filter_append($handle, $filter, STREAM_FILTER_WRITE);
  150. if (!$filter) {
  151. return false;
  152. }
  153. // Seek to the offset start if possible
  154. $this->seek($offsetStart);
  155. while ($data = fread($this->stream, 8096)) {
  156. fwrite($handle, $data);
  157. }
  158. fclose($this->stream);
  159. $this->stream = $handle;
  160. stream_filter_remove($filter);
  161. $stat = fstat($this->stream);
  162. $this->size = $stat['size'];
  163. $this->rebuildCache();
  164. $this->seek(0);
  165. // Remove any existing rewind function as the underlying stream has been replaced
  166. $this->rewindFunction = null;
  167. return true;
  168. }
  169. }