LazyOpenStream.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\StreamInterface;
  5. /**
  6. * Lazily reads or writes to a file that is opened only after an IO operation
  7. * take place on the stream.
  8. */
  9. final class LazyOpenStream implements StreamInterface
  10. {
  11. use StreamDecoratorTrait;
  12. /** @var string */
  13. private $filename;
  14. /** @var string */
  15. private $mode;
  16. /**
  17. * @var StreamInterface
  18. */
  19. private $stream;
  20. /**
  21. * @param string $filename File to lazily open
  22. * @param string $mode fopen mode to use when opening the stream
  23. */
  24. public function __construct(string $filename, string $mode)
  25. {
  26. $this->filename = $filename;
  27. $this->mode = $mode;
  28. // unsetting the property forces the first access to go through
  29. // __get().
  30. unset($this->stream);
  31. }
  32. /**
  33. * Creates the underlying stream lazily when required.
  34. */
  35. protected function createStream(): StreamInterface
  36. {
  37. return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode));
  38. }
  39. }