ZipNewData.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace PhpZip\Model\Data;
  3. use PhpZip\Model\ZipData;
  4. use PhpZip\Model\ZipEntry;
  5. /**
  6. * Class ZipNewData.
  7. */
  8. class ZipNewData implements ZipData
  9. {
  10. /** @var resource */
  11. private $stream;
  12. /** @var ZipEntry */
  13. private $zipEntry;
  14. /**
  15. * ZipStringData constructor.
  16. *
  17. * @param ZipEntry $zipEntry
  18. * @param string|resource $data
  19. */
  20. public function __construct(ZipEntry $zipEntry, $data)
  21. {
  22. $this->zipEntry = $zipEntry;
  23. if (\is_string($data)) {
  24. $zipEntry->setUncompressedSize(\strlen($data));
  25. if (!($handle = fopen('php://temp', 'w+b'))) {
  26. throw new \RuntimeException('Temp resource can not open from write.');
  27. }
  28. fwrite($handle, $data);
  29. rewind($handle);
  30. $this->stream = $handle;
  31. } elseif (\is_resource($data)) {
  32. $this->stream = $data;
  33. }
  34. }
  35. /**
  36. * @return resource returns stream data
  37. */
  38. public function getDataAsStream()
  39. {
  40. if (!\is_resource($this->stream)) {
  41. throw new \LogicException(sprintf('Resource was closed (entry=%s).', $this->zipEntry->getName()));
  42. }
  43. return $this->stream;
  44. }
  45. /**
  46. * @return string returns data as string
  47. */
  48. public function getDataAsString()
  49. {
  50. $stream = $this->getDataAsStream();
  51. $pos = ftell($stream);
  52. try {
  53. rewind($stream);
  54. return stream_get_contents($stream);
  55. } finally {
  56. fseek($stream, $pos);
  57. }
  58. }
  59. /**
  60. * @param resource $outStream
  61. */
  62. public function copyDataToStream($outStream)
  63. {
  64. $stream = $this->getDataAsStream();
  65. rewind($stream);
  66. stream_copy_to_stream($stream, $outStream);
  67. }
  68. public function __destruct()
  69. {
  70. if (\is_resource($this->stream)) {
  71. fclose($this->stream);
  72. }
  73. }
  74. }