EpubWriter.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of the nelexa/zip package.
  5. * (c) Ne-Lexa <https://github.com/Ne-Lexa/php-zip>
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. namespace PhpZip\Tests\Internal\Epub;
  10. use PhpZip\Constants\ZipCompressionMethod;
  11. use PhpZip\Constants\ZipPlatform;
  12. use PhpZip\Exception\ZipUnsupportMethodException;
  13. use PhpZip\IO\ZipWriter;
  14. use PhpZip\Model\Data\ZipNewData;
  15. use PhpZip\Model\ZipEntry;
  16. /**
  17. * Class EpubWriter.
  18. *
  19. * @property EpubZipContainer $zipContainer
  20. */
  21. class EpubWriter extends ZipWriter
  22. {
  23. /**
  24. * @throws ZipUnsupportMethodException
  25. */
  26. protected function beforeWrite(): void
  27. {
  28. parent::beforeWrite();
  29. if (!$this->zipContainer->hasEntry('mimetype')) {
  30. $zipEntry = new ZipEntry('mimetype');
  31. $zipEntry->setCreatedOS(ZipPlatform::OS_DOS);
  32. $zipEntry->setExtractedOS(ZipPlatform::OS_DOS);
  33. $zipEntry->setCompressionMethod(ZipCompressionMethod::STORED);
  34. $zipEntry->setData(new ZipNewData($zipEntry, 'application/epub+zip'));
  35. $this->zipContainer->addEntry($zipEntry);
  36. }
  37. $this->sortEntries();
  38. }
  39. private function sortEntries(): void
  40. {
  41. $this->zipContainer->sortByEntry(
  42. static function (ZipEntry $a, ZipEntry $b) {
  43. if (strcasecmp($a->getName(), 'mimetype') === 0) {
  44. return -1;
  45. }
  46. if (strcasecmp($b->getName(), 'mimetype') === 0) {
  47. return 1;
  48. }
  49. if ($a->isDirectory() && $b->isDirectory()) {
  50. return strcmp($a->getName(), $b->getName());
  51. }
  52. if ($a->isDirectory()) {
  53. return -1;
  54. }
  55. if ($b->isDirectory()) {
  56. return 1;
  57. }
  58. return strcmp($a->getName(), $b->getName());
  59. }
  60. );
  61. }
  62. }