2
0

EpubWriter.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace PhpZip\Tests\Internal\Epub;
  3. use PhpZip\Constants\ZipCompressionMethod;
  4. use PhpZip\Constants\ZipPlatform;
  5. use PhpZip\Exception\ZipUnsupportMethodException;
  6. use PhpZip\IO\ZipWriter;
  7. use PhpZip\Model\Data\ZipNewData;
  8. use PhpZip\Model\ZipEntry;
  9. /**
  10. * Class EpubWriter.
  11. *
  12. * @property EpubZipContainer $zipContainer
  13. */
  14. class EpubWriter extends ZipWriter
  15. {
  16. /**
  17. * @throws ZipUnsupportMethodException
  18. */
  19. protected function beforeWrite()
  20. {
  21. parent::beforeWrite();
  22. if (!$this->zipContainer->hasEntry('mimetype')) {
  23. $zipEntry = new ZipEntry('mimetype');
  24. $zipEntry->setCreatedOS(ZipPlatform::OS_DOS);
  25. $zipEntry->setExtractedOS(ZipPlatform::OS_DOS);
  26. $zipEntry->setCompressionMethod(ZipCompressionMethod::STORED);
  27. $zipEntry->setData(new ZipNewData($zipEntry, 'application/epub+zip'));
  28. $this->zipContainer->addEntry($zipEntry);
  29. }
  30. $this->sortEntries();
  31. }
  32. private function sortEntries()
  33. {
  34. $this->zipContainer->sortByEntry(
  35. static function (ZipEntry $a, ZipEntry $b) {
  36. if (strcasecmp($a->getName(), 'mimetype') === 0) {
  37. return -1;
  38. }
  39. if (strcasecmp($b->getName(), 'mimetype') === 0) {
  40. return 1;
  41. }
  42. if ($a->isDirectory() && $b->isDirectory()) {
  43. return strcmp($a->getName(), $b->getName());
  44. }
  45. if ($a->isDirectory()) {
  46. return -1;
  47. }
  48. if ($b->isDirectory()) {
  49. return 1;
  50. }
  51. return strcmp($a->getName(), $b->getName());
  52. }
  53. );
  54. }
  55. }