ZipSourceEntry.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. * @author Ne-Lexa alexey@nelexa.ru
  10. * @license MIT
  11. */
  12. class ZipSourceEntry extends ZipAbstractEntry
  13. {
  14. /**
  15. * Max size cached content in memory.
  16. */
  17. const MAX_SIZE_CACHED_CONTENT_IN_MEMORY = 524288; // 512 kb
  18. /**
  19. * @var ZipInputStreamInterface
  20. */
  21. protected $inputStream;
  22. /**
  23. * @var string|resource Cached entry content.
  24. */
  25. protected $entryContent;
  26. /**
  27. * @var string
  28. */
  29. protected $readPassword;
  30. /**
  31. * @var bool
  32. */
  33. private $clone = false;
  34. /**
  35. * ZipSourceEntry constructor.
  36. * @param ZipInputStreamInterface $inputStream
  37. */
  38. public function __construct(ZipInputStreamInterface $inputStream)
  39. {
  40. parent::__construct();
  41. $this->inputStream = $inputStream;
  42. }
  43. /**
  44. * @return ZipInputStreamInterface
  45. */
  46. public function getInputStream()
  47. {
  48. return $this->inputStream;
  49. }
  50. /**
  51. * Returns an string content of the given entry.
  52. *
  53. * @return string
  54. * @throws ZipException
  55. */
  56. public function getEntryContent()
  57. {
  58. if (null === $this->entryContent) {
  59. $content = $this->inputStream->readEntryContent($this);
  60. if ($this->getSize() < self::MAX_SIZE_CACHED_CONTENT_IN_MEMORY) {
  61. $this->entryContent = $content;
  62. } else {
  63. $this->entryContent = fopen('php://temp', 'rb');
  64. fwrite($this->entryContent, $content);
  65. }
  66. return $content;
  67. }
  68. if (is_resource($this->entryContent)) {
  69. return stream_get_contents($this->entryContent, -1, 0);
  70. }
  71. return $this->entryContent;
  72. }
  73. /**
  74. * Clone extra fields
  75. */
  76. public function __clone()
  77. {
  78. $this->clone = true;
  79. parent::__clone();
  80. }
  81. public function __destruct()
  82. {
  83. if (!$this->clone && null !== $this->entryContent && is_resource($this->entryContent)) {
  84. fclose($this->entryContent);
  85. }
  86. }
  87. }