ZipFileData.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace PhpZip\Model\Data;
  3. use PhpZip\Exception\ZipException;
  4. use PhpZip\Model\ZipData;
  5. use PhpZip\Model\ZipEntry;
  6. /**
  7. * Class ZipFileData.
  8. */
  9. class ZipFileData implements ZipData
  10. {
  11. /** @var \SplFileInfo */
  12. private $file;
  13. /**
  14. * ZipStringData constructor.
  15. *
  16. * @param ZipEntry $zipEntry
  17. * @param \SplFileInfo $fileInfo
  18. *
  19. * @throws ZipException
  20. */
  21. public function __construct(ZipEntry $zipEntry, \SplFileInfo $fileInfo)
  22. {
  23. if (!$fileInfo->isFile()) {
  24. throw new ZipException('$fileInfo is not a file.');
  25. }
  26. if (!$fileInfo->isReadable()) {
  27. throw new ZipException('$fileInfo is not readable.');
  28. }
  29. $this->file = $fileInfo;
  30. $zipEntry->setUncompressedSize($fileInfo->getSize());
  31. }
  32. /**
  33. * @throws ZipException
  34. *
  35. * @return resource returns stream data
  36. */
  37. public function getDataAsStream()
  38. {
  39. if (!$this->file->isReadable()) {
  40. throw new ZipException(sprintf('The %s file is no longer readable.', $this->file->getPathname()));
  41. }
  42. return fopen($this->file->getPathname(), 'rb');
  43. }
  44. /**
  45. * @throws ZipException
  46. *
  47. * @return string returns data as string
  48. */
  49. public function getDataAsString()
  50. {
  51. if (!$this->file->isReadable()) {
  52. throw new ZipException(sprintf('The %s file is no longer readable.', $this->file->getPathname()));
  53. }
  54. return file_get_contents($this->file->getPathname());
  55. }
  56. /**
  57. * @param resource $outStream
  58. *
  59. * @throws ZipException
  60. */
  61. public function copyDataToStream($outStream)
  62. {
  63. try {
  64. $stream = $this->getDataAsStream();
  65. stream_copy_to_stream($stream, $outStream);
  66. } finally {
  67. fclose($stream);
  68. }
  69. }
  70. }