GuzzleStreamWrapper.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <?php
  2. namespace GuzzleHttp\Stream;
  3. /**
  4. * Converts Guzzle streams into PHP stream resources.
  5. */
  6. class GuzzleStreamWrapper
  7. {
  8. /** @var resource */
  9. public $context;
  10. /** @var StreamInterface */
  11. private $stream;
  12. /** @var string r, r+, or w */
  13. private $mode;
  14. /**
  15. * Returns a resource representing the stream.
  16. *
  17. * @param StreamInterface $stream The stream to get a resource for
  18. *
  19. * @return resource
  20. * @throws \InvalidArgumentException if stream is not readable or writable
  21. */
  22. public static function getResource(StreamInterface $stream)
  23. {
  24. self::register();
  25. if ($stream->isReadable()) {
  26. $mode = $stream->isWritable() ? 'r+' : 'r';
  27. } elseif ($stream->isWritable()) {
  28. $mode = 'w';
  29. } else {
  30. throw new \InvalidArgumentException('The stream must be readable, '
  31. . 'writable, or both.');
  32. }
  33. return fopen('guzzle://stream', $mode, null, stream_context_create([
  34. 'guzzle' => ['stream' => $stream]
  35. ]));
  36. }
  37. /**
  38. * Registers the stream wrapper if needed
  39. */
  40. public static function register()
  41. {
  42. if (!in_array('guzzle', stream_get_wrappers())) {
  43. stream_wrapper_register('guzzle', __CLASS__);
  44. }
  45. }
  46. public function stream_open($path, $mode, $options, &$opened_path)
  47. {
  48. $options = stream_context_get_options($this->context);
  49. if (!isset($options['guzzle']['stream'])) {
  50. return false;
  51. }
  52. $this->mode = $mode;
  53. $this->stream = $options['guzzle']['stream'];
  54. return true;
  55. }
  56. public function stream_read($count)
  57. {
  58. return $this->stream->read($count);
  59. }
  60. public function stream_write($data)
  61. {
  62. return (int) $this->stream->write($data);
  63. }
  64. public function stream_tell()
  65. {
  66. return $this->stream->tell();
  67. }
  68. public function stream_eof()
  69. {
  70. return $this->stream->eof();
  71. }
  72. public function stream_seek($offset, $whence)
  73. {
  74. return $this->stream->seek($offset, $whence);
  75. }
  76. public function stream_stat()
  77. {
  78. static $modeMap = [
  79. 'r' => 33060,
  80. 'r+' => 33206,
  81. 'w' => 33188
  82. ];
  83. return [
  84. 'dev' => 0,
  85. 'ino' => 0,
  86. 'mode' => $modeMap[$this->mode],
  87. 'nlink' => 0,
  88. 'uid' => 0,
  89. 'gid' => 0,
  90. 'rdev' => 0,
  91. 'size' => $this->stream->getSize() ?: 0,
  92. 'atime' => 0,
  93. 'mtime' => 0,
  94. 'ctime' => 0,
  95. 'blksize' => 0,
  96. 'blocks' => 0
  97. ];
  98. }
  99. }