Nav apraksta

StreamWrapper.php 2.7KB

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