ZipFileData.php 1.7 KB

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