ZipSourceEntry.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace PhpZip\Model\Entry;
  3. use PhpZip\Exception\ZipException;
  4. use PhpZip\Stream\ZipInputStreamInterface;
  5. /**
  6. * This class is used to represent a ZIP file entry.
  7. *
  8. * @see https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT .ZIP File Format Specification
  9. *
  10. * @author Ne-Lexa alexey@nelexa.ru
  11. * @license MIT
  12. */
  13. class ZipSourceEntry extends ZipAbstractEntry
  14. {
  15. /** Max size cached content in memory. */
  16. const MAX_SIZE_CACHED_CONTENT_IN_MEMORY = 524288; // 512 kb
  17. /** @var ZipInputStreamInterface */
  18. protected $inputStream;
  19. /** @var string|resource cached entry content */
  20. protected $entryContent;
  21. /** @var bool */
  22. private $clone = false;
  23. /**
  24. * ZipSourceEntry constructor.
  25. *
  26. * @param ZipInputStreamInterface $inputStream
  27. */
  28. public function __construct(ZipInputStreamInterface $inputStream)
  29. {
  30. parent::__construct();
  31. $this->inputStream = $inputStream;
  32. }
  33. /**
  34. * @return ZipInputStreamInterface
  35. */
  36. public function getInputStream()
  37. {
  38. return $this->inputStream;
  39. }
  40. /**
  41. * Returns an string content of the given entry.
  42. *
  43. * @throws ZipException
  44. *
  45. * @return string
  46. */
  47. public function getEntryContent()
  48. {
  49. if ($this->entryContent === null) {
  50. // In order not to unpack again, we cache the content in memory or on disk
  51. $content = $this->inputStream->readEntryContent($this);
  52. if ($this->getSize() < self::MAX_SIZE_CACHED_CONTENT_IN_MEMORY) {
  53. $this->entryContent = $content;
  54. } else {
  55. $this->entryContent = fopen('php://temp', 'r+b');
  56. fwrite($this->entryContent, $content);
  57. }
  58. return $content;
  59. }
  60. if (\is_resource($this->entryContent)) {
  61. rewind($this->entryContent);
  62. return stream_get_contents($this->entryContent);
  63. }
  64. return $this->entryContent;
  65. }
  66. /**
  67. * Clone extra fields.
  68. */
  69. public function __clone()
  70. {
  71. $this->clone = true;
  72. parent::__clone();
  73. }
  74. public function __destruct()
  75. {
  76. if (!$this->clone && $this->entryContent !== null && \is_resource($this->entryContent)) {
  77. fclose($this->entryContent);
  78. }
  79. }
  80. }