2
0

ZipFileTest.php 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383
  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;
  10. use GuzzleHttp\Psr7\Response;
  11. use PhpZip\Constants\ZipCompressionLevel;
  12. use PhpZip\Constants\ZipCompressionMethod;
  13. use PhpZip\Constants\ZipPlatform;
  14. use PhpZip\Exception\InvalidArgumentException;
  15. use PhpZip\Exception\ZipEntryNotFoundException;
  16. use PhpZip\Exception\ZipException;
  17. use PhpZip\Exception\ZipUnsupportMethodException;
  18. use PhpZip\Model\Data\ZipFileData;
  19. use PhpZip\Model\ZipEntry;
  20. use PhpZip\Util\FilesUtil;
  21. use PhpZip\ZipFile;
  22. /**
  23. * ZipFile test.
  24. *
  25. * @internal
  26. *
  27. * @small
  28. */
  29. class ZipFileTest extends ZipTestCase
  30. {
  31. /**
  32. * @throws ZipException
  33. */
  34. public function testOpenFileCantExists(): void
  35. {
  36. $this->expectException(ZipException::class);
  37. $this->expectExceptionMessage('does not exist');
  38. $zipFile = new ZipFile();
  39. $zipFile->openFile(uniqid('', false));
  40. }
  41. /**
  42. * @throws ZipException
  43. */
  44. public function testOpenFileCantOpen(): void
  45. {
  46. static::skipTestForWindows();
  47. static::skipTestForRootUser();
  48. $this->expectException(InvalidArgumentException::class);
  49. $this->expectExceptionMessage('Permission denied');
  50. static::assertNotFalse(file_put_contents($this->outputFilename, 'content'));
  51. static::assertTrue(chmod($this->outputFilename, 0222));
  52. $zipFile = new ZipFile();
  53. $zipFile->openFile($this->outputFilename);
  54. }
  55. /**
  56. * @throws ZipException
  57. */
  58. public function testOpenFileEmptyFile(): void
  59. {
  60. $this->expectException(ZipException::class);
  61. $this->expectExceptionMessage('Corrupt zip file');
  62. static::assertNotFalse(touch($this->outputFilename));
  63. $zipFile = new ZipFile();
  64. $zipFile->openFile($this->outputFilename);
  65. }
  66. /**
  67. * @throws ZipException
  68. * @throws \Exception
  69. */
  70. public function testOpenFileInvalidZip(): void
  71. {
  72. $this->expectException(ZipException::class);
  73. $this->expectExceptionMessage('Invalid zip file. The end of the central directory could not be found.');
  74. static::assertNotFalse(file_put_contents($this->outputFilename, random_bytes(255)));
  75. $zipFile = new ZipFile();
  76. $zipFile->openFile($this->outputFilename);
  77. }
  78. /**
  79. * @throws ZipException
  80. */
  81. public function testOpenFromStringEmptyString(): void
  82. {
  83. $this->expectException(InvalidArgumentException::class);
  84. $this->expectExceptionMessage('Empty string passed');
  85. $zipFile = new ZipFile();
  86. $zipFile->openFromString('');
  87. }
  88. /**
  89. * @throws ZipException
  90. * @throws \Exception
  91. */
  92. public function testOpenFromStringInvalidZip(): void
  93. {
  94. $this->expectException(ZipException::class);
  95. $this->expectExceptionMessage('Invalid zip file. The end of the central directory could not be found.');
  96. $zipFile = new ZipFile();
  97. $zipFile->openFromString(random_bytes(255));
  98. }
  99. /**
  100. * @throws ZipException
  101. */
  102. public function testOpenFromString(): void
  103. {
  104. $zipFile = new ZipFile();
  105. $zipFile->addFromString('file', 'content');
  106. $zipFile['file2'] = 'content 2';
  107. $zipContents = $zipFile->outputAsString();
  108. $zipFile->close();
  109. $zipFile->openFromString($zipContents);
  110. static::assertSame($zipFile->count(), 2);
  111. static::assertTrue(isset($zipFile['file']));
  112. static::assertTrue(isset($zipFile['file2']));
  113. static::assertSame($zipFile['file'], 'content');
  114. static::assertSame($zipFile['file2'], 'content 2');
  115. $zipFile->close();
  116. }
  117. /**
  118. * @throws ZipException
  119. */
  120. public function testOpenFromStreamNullStream(): void
  121. {
  122. $this->expectException(InvalidArgumentException::class);
  123. $this->expectExceptionMessage('Stream must be a resource');
  124. $zipFile = new ZipFile();
  125. $zipFile->openFromStream(null);
  126. }
  127. /**
  128. * @throws ZipException
  129. */
  130. public function testOpenFromStreamInvalidResourceType(): void
  131. {
  132. $this->expectException(InvalidArgumentException::class);
  133. $this->expectExceptionMessage('Stream must be a resource');
  134. $zipFile = new ZipFile();
  135. /** @noinspection PhpParamsInspection */
  136. $zipFile->openFromStream('stream resource');
  137. }
  138. /**
  139. * @throws ZipException
  140. */
  141. public function testOpenFromStreamInvalidResourceType3(): void
  142. {
  143. $this->expectException(InvalidArgumentException::class);
  144. $this->expectExceptionMessage('Directory streams are not supported');
  145. $zipFile = new ZipFile();
  146. $zipFile->openFromStream(opendir(__DIR__));
  147. }
  148. /**
  149. * @throws ZipException
  150. *
  151. * @noinspection PhpUsageOfSilenceOperatorInspection
  152. * @noinspection NestedPositiveIfStatementsInspection
  153. */
  154. public function testOpenFromStreamNoSeekable(): void
  155. {
  156. $this->expectException(InvalidArgumentException::class);
  157. $this->expectExceptionMessage('The stream wrapper type "http" is not supported');
  158. if (!$fp = @fopen('http://localhost', 'rb')) {
  159. if (!$fp = @fopen('http://example.org', 'rb')) {
  160. static::markTestSkipped('not connected to localhost or remote host');
  161. }
  162. }
  163. $zipFile = new ZipFile();
  164. $zipFile->openFromStream($fp);
  165. }
  166. /**
  167. * @throws ZipException
  168. */
  169. public function testOpenFromStreamEmptyContents(): void
  170. {
  171. $this->expectException(ZipException::class);
  172. $this->expectExceptionMessage('Corrupt zip file');
  173. $fp = fopen($this->outputFilename, 'w+b');
  174. $zipFile = new ZipFile();
  175. $zipFile->openFromStream($fp);
  176. }
  177. /**
  178. * @throws ZipException
  179. * @throws \Exception
  180. */
  181. public function testOpenFromStreamInvalidZip(): void
  182. {
  183. $this->expectException(ZipException::class);
  184. $this->expectExceptionMessage('Invalid zip file. The end of the central directory could not be found.');
  185. $fp = fopen($this->outputFilename, 'w+b');
  186. fwrite($fp, random_bytes(255));
  187. $zipFile = new ZipFile();
  188. $zipFile->openFromStream($fp);
  189. }
  190. /**
  191. * @throws ZipException
  192. */
  193. public function testOpenFromStream(): void
  194. {
  195. $zipFile = new ZipFile();
  196. $zipFile
  197. ->addFromString('file', 'content')
  198. ->saveAsFile($this->outputFilename)
  199. ->close()
  200. ;
  201. $handle = fopen($this->outputFilename, 'rb');
  202. $zipFile->openFromStream($handle);
  203. static::assertSame($zipFile->count(), 1);
  204. static::assertTrue(isset($zipFile['file']));
  205. static::assertSame($zipFile['file'], 'content');
  206. $zipFile->close();
  207. }
  208. /**
  209. * Test create, open and extract empty archive.
  210. *
  211. * @throws ZipException
  212. */
  213. public function testEmptyArchive(): void
  214. {
  215. $zipFile = new ZipFile();
  216. $zipFile
  217. ->saveAsFile($this->outputFilename)
  218. ->close()
  219. ;
  220. static::assertCorrectEmptyZip($this->outputFilename);
  221. static::assertTrue(mkdir($this->outputDirname, 0755, true));
  222. $zipFile->openFile($this->outputFilename);
  223. static::assertSame($zipFile->count(), 0);
  224. $zipFile
  225. ->extractTo($this->outputDirname)
  226. ->close()
  227. ;
  228. static::assertTrue(FilesUtil::isEmptyDir($this->outputDirname));
  229. }
  230. /**
  231. * No modified archive.
  232. *
  233. * @throws ZipException
  234. *
  235. * @see ZipOutputFile::create()
  236. */
  237. public function testNoModifiedArchive(): void
  238. {
  239. static::assertTrue(mkdir($this->outputDirname, 0755, true));
  240. $fileActual = $this->outputDirname . \DIRECTORY_SEPARATOR . 'file_actual.zip';
  241. $fileExpected = $this->outputDirname . \DIRECTORY_SEPARATOR . 'file_expected.zip';
  242. $zipFile = new ZipFile();
  243. $zipFile->addDirRecursive(__DIR__ . '/../src');
  244. $sourceCount = $zipFile->count();
  245. static::assertTrue($sourceCount > 0);
  246. $zipFile
  247. ->saveAsFile($fileActual)
  248. ->close()
  249. ;
  250. static::assertCorrectZipArchive($fileActual);
  251. $zipFile
  252. ->openFile($fileActual)
  253. ->saveAsFile($fileExpected)
  254. ;
  255. static::assertCorrectZipArchive($fileExpected);
  256. $zipFileExpected = new ZipFile();
  257. $zipFileExpected->openFile($fileExpected);
  258. static::assertSame($zipFile->count(), $sourceCount);
  259. static::assertSame($zipFileExpected->count(), $zipFile->count());
  260. static::assertSame($zipFileExpected->getListFiles(), $zipFile->getListFiles());
  261. foreach ($zipFile as $entryName => $content) {
  262. static::assertSame($zipFileExpected[$entryName], $content);
  263. }
  264. $zipFileExpected->close();
  265. $zipFile->close();
  266. }
  267. /**
  268. * Create archive and add files.
  269. *
  270. * @throws ZipException
  271. *
  272. * @see ZipOutputFile::addFromFile()
  273. * @see ZipOutputFile::addFromStream()
  274. * @see ZipFile::getEntryContents()
  275. * @see ZipOutputFile::addFromString()
  276. */
  277. public function testCreateArchiveAndAddFiles(): void
  278. {
  279. $outputFromString = file_get_contents(__FILE__);
  280. $outputFromString2 = file_get_contents(\dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'README.md');
  281. $outputFromFile = file_get_contents(\dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'phpunit.xml');
  282. $outputFromStream = file_get_contents(\dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'composer.json');
  283. $filenameFromString = basename(__FILE__);
  284. $filenameFromString2 = 'test_file.txt';
  285. $filenameFromFile = 'data/test file.txt';
  286. $filenameFromStream = 'data/ডিরেক্টরি/αρχείο.json';
  287. $emptyDirName = 'empty dir/пустой каталог/空目錄/ไดเรกทอรีที่ว่างเปล่า/';
  288. $emptyDirName2 = 'empty dir/пустой каталог/';
  289. $emptyDirName3 = 'empty dir/пустой каталог/ещё один пустой каталог/';
  290. $tempFile = tempnam(sys_get_temp_dir(), 'txt');
  291. file_put_contents($tempFile, $outputFromFile);
  292. $tempStream = tmpfile();
  293. fwrite($tempStream, $outputFromStream);
  294. $zipFile = new ZipFile();
  295. $zipFile
  296. ->addFromString($filenameFromString, $outputFromString)
  297. ->addFile($tempFile, $filenameFromFile)
  298. ->addFromStream($tempStream, $filenameFromStream)
  299. ->addEmptyDir($emptyDirName)
  300. ;
  301. $zipFile[$filenameFromString2] = $outputFromString2;
  302. $zipFile[$emptyDirName2] = null;
  303. $zipFile[$emptyDirName3] = 'this content ignoring';
  304. static::assertSame(\count($zipFile), 7);
  305. $zipFile
  306. ->saveAsFile($this->outputFilename)
  307. ->close()
  308. ;
  309. unlink($tempFile);
  310. static::assertCorrectZipArchive($this->outputFilename);
  311. $zipFile->openFile($this->outputFilename);
  312. static::assertSame(\count($zipFile), 7);
  313. static::assertSame($zipFile[$filenameFromString], $outputFromString);
  314. static::assertSame($zipFile[$filenameFromFile], $outputFromFile);
  315. static::assertSame($zipFile[$filenameFromStream], $outputFromStream);
  316. static::assertSame($zipFile[$filenameFromString2], $outputFromString2);
  317. static::assertTrue(isset($zipFile[$emptyDirName]));
  318. static::assertTrue(isset($zipFile[$emptyDirName2]));
  319. static::assertTrue(isset($zipFile[$emptyDirName3]));
  320. static::assertTrue($zipFile->isDirectory($emptyDirName));
  321. static::assertTrue($zipFile->isDirectory($emptyDirName2));
  322. static::assertTrue($zipFile->isDirectory($emptyDirName3));
  323. $listFiles = $zipFile->getListFiles();
  324. static::assertSame($listFiles[0], $filenameFromString);
  325. static::assertSame($listFiles[1], $filenameFromFile);
  326. static::assertSame($listFiles[2], $filenameFromStream);
  327. static::assertSame($listFiles[3], $emptyDirName);
  328. static::assertSame($listFiles[4], $filenameFromString2);
  329. static::assertSame($listFiles[5], $emptyDirName2);
  330. static::assertSame($listFiles[6], $emptyDirName3);
  331. $zipFile->close();
  332. }
  333. /**
  334. * @throws ZipException
  335. */
  336. public function testEmptyContent(): void
  337. {
  338. $zipFile = new ZipFile();
  339. $zipFile['file'] = '';
  340. $zipFile->saveAsFile($this->outputFilename);
  341. $zipFile->close();
  342. $zipFile->openFile($this->outputFilename);
  343. static::assertSame($zipFile['file'], '');
  344. $zipFile->close();
  345. }
  346. /**
  347. * Test compression method from image file.
  348. *
  349. * @throws ZipException
  350. */
  351. public function testCompressionMethodFromImageMimeType(): void
  352. {
  353. if (!\function_exists('mime_content_type')) {
  354. static::markTestSkipped('Function mime_content_type not exists');
  355. }
  356. $outputFilename = $this->outputFilename;
  357. $this->outputFilename .= '.gif';
  358. static::assertNotFalse(
  359. file_put_contents(
  360. $this->outputFilename,
  361. base64_decode('R0lGODlhAQABAJAAAP8AAAAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==', true)
  362. )
  363. );
  364. $basename = basename($this->outputFilename);
  365. $zipFile = new ZipFile();
  366. $zipFile->addFile($this->outputFilename, $basename);
  367. $zipFile->saveAsFile($outputFilename);
  368. unlink($this->outputFilename);
  369. $this->outputFilename = $outputFilename;
  370. $zipFile->openFile($this->outputFilename);
  371. $zipEntry = $zipFile->getEntry($basename);
  372. static::assertSame($zipEntry->getCompressionMethod(), ZipCompressionMethod::STORED);
  373. $zipFile->close();
  374. }
  375. /**
  376. * Rename zip entry name.
  377. *
  378. * @throws ZipException
  379. */
  380. public function testRename(): void
  381. {
  382. $oldName = basename(__FILE__);
  383. $newName = 'tests/' . $oldName;
  384. $zipFile = new ZipFile();
  385. $zipFile->addDir(__DIR__);
  386. $zipFile->saveAsFile($this->outputFilename);
  387. $zipFile->close();
  388. static::assertCorrectZipArchive($this->outputFilename);
  389. $zipFile->openFile($this->outputFilename);
  390. $zipFile->rename($oldName, $newName);
  391. $zipFile->addFromString('file1.txt', 'content');
  392. $zipFile->addFromString('file2.txt', 'content');
  393. $zipFile->addFromString('file3.txt', 'content');
  394. $zipFile->rename('file1.txt', 'file_long_name.txt');
  395. $zipFile->rename('file2.txt', 'file4.txt');
  396. $zipFile->rename('file3.txt', 'fi.txt');
  397. $zipFile->saveAsFile($this->outputFilename);
  398. $zipFile->close();
  399. static::assertCorrectZipArchive($this->outputFilename);
  400. $zipFile->openFile($this->outputFilename);
  401. static::assertFalse(isset($zipFile[$oldName]));
  402. static::assertTrue(isset($zipFile[$newName]));
  403. static::assertFalse(isset($zipFile['file1.txt']));
  404. static::assertFalse(isset($zipFile['file2.txt']));
  405. static::assertFalse(isset($zipFile['file3.txt']));
  406. static::assertTrue(isset($zipFile['file_long_name.txt']));
  407. static::assertTrue(isset($zipFile['file4.txt']));
  408. static::assertTrue(isset($zipFile['fi.txt']));
  409. $zipFile->close();
  410. }
  411. /**
  412. * @throws ZipException
  413. */
  414. public function testRenameEntryToExistsNewEntry(): void
  415. {
  416. $this->expectException(InvalidArgumentException::class);
  417. $this->expectExceptionMessage('already exists');
  418. $zipFile = new ZipFile();
  419. $zipFile['file'] = 'content';
  420. $zipFile['file2'] = 'content 2';
  421. $zipFile->saveAsFile($this->outputFilename);
  422. $zipFile->close();
  423. $zipFile = new ZipFile();
  424. $zipFile->openFile($this->outputFilename);
  425. $zipFile->rename('file2', 'file');
  426. }
  427. /**
  428. * @throws ZipException
  429. */
  430. public function testRenameEntryNotFound(): void
  431. {
  432. $this->expectException(ZipEntryNotFoundException::class);
  433. $zipFile = new ZipFile();
  434. $zipFile['file'] = 'content';
  435. $zipFile['file2'] = 'content 2';
  436. $zipFile->saveAsFile($this->outputFilename);
  437. $zipFile->close();
  438. $zipFile = new ZipFile();
  439. $zipFile->openFile($this->outputFilename);
  440. $zipFile->rename('file2.bak', 'file3');
  441. }
  442. /**
  443. * Delete entry from name.
  444. *
  445. * @throws ZipException
  446. */
  447. public function testDeleteFromName(): void
  448. {
  449. $inputDir = \dirname(__DIR__) . \DIRECTORY_SEPARATOR;
  450. $deleteEntryName = 'composer.json';
  451. $zipFile = new ZipFile();
  452. $zipFile->addDir($inputDir);
  453. $zipFile->saveAsFile($this->outputFilename);
  454. $zipFile->close();
  455. static::assertCorrectZipArchive($this->outputFilename);
  456. $zipFile->openFile($this->outputFilename);
  457. $zipFile->deleteFromName($deleteEntryName);
  458. $zipFile->saveAsFile($this->outputFilename);
  459. $zipFile->close();
  460. static::assertCorrectZipArchive($this->outputFilename);
  461. $zipFile->openFile($this->outputFilename);
  462. static::assertFalse(isset($zipFile[$deleteEntryName]));
  463. $zipFile->close();
  464. }
  465. /**
  466. * @throws ZipEntryNotFoundException
  467. * @throws ZipException
  468. */
  469. public function testDeleteNewEntry(): void
  470. {
  471. $zipFile = new ZipFile();
  472. $zipFile['entry1'] = '';
  473. $zipFile['entry2'] = '';
  474. $zipFile->deleteFromName('entry2');
  475. $zipFile->saveAsFile($this->outputFilename);
  476. $zipFile->close();
  477. $zipFile->openFile($this->outputFilename);
  478. static::assertSame(\count($zipFile), 1);
  479. static::assertTrue(isset($zipFile['entry1']));
  480. static::assertFalse(isset($zipFile['entry2']));
  481. $zipFile->close();
  482. }
  483. /**
  484. * @throws ZipEntryNotFoundException
  485. */
  486. public function testDeleteFromNameNotFoundEntry(): void
  487. {
  488. $this->expectException(ZipEntryNotFoundException::class);
  489. $zipFile = new ZipFile();
  490. $zipFile->deleteFromName('entry');
  491. }
  492. public function testCatchNotFoundEntry(): void
  493. {
  494. $entryName = 'entry';
  495. $zipFile = new ZipFile();
  496. try {
  497. $zipFile->getEntry($entryName);
  498. } catch (ZipEntryNotFoundException $e) {
  499. static::assertSame($e->getEntryName(), $entryName);
  500. }
  501. }
  502. /**
  503. * Delete zip entries from glob pattern.
  504. *
  505. * @throws ZipException
  506. */
  507. public function testDeleteFromGlob(): void
  508. {
  509. $inputDir = \dirname(__DIR__);
  510. $zipFile = new ZipFile();
  511. $zipFile->addFilesFromGlobRecursive($inputDir, '**.{xml,json,md}');
  512. static::assertTrue(isset($zipFile['composer.json']));
  513. static::assertTrue(isset($zipFile['phpunit.xml']));
  514. $zipFile->saveAsFile($this->outputFilename);
  515. $zipFile->close();
  516. static::assertCorrectZipArchive($this->outputFilename);
  517. $zipFile->openFile($this->outputFilename);
  518. static::assertTrue(isset($zipFile['composer.json']));
  519. static::assertTrue(isset($zipFile['phpunit.xml']));
  520. $zipFile->deleteFromGlob('**.{xml,json}');
  521. static::assertFalse(isset($zipFile['composer.json']));
  522. static::assertFalse(isset($zipFile['phpunit.xml']));
  523. $zipFile->saveAsFile($this->outputFilename);
  524. $zipFile->close();
  525. static::assertCorrectZipArchive($this->outputFilename);
  526. $zipFile->openFile($this->outputFilename);
  527. static::assertTrue($zipFile->count() > 0);
  528. foreach ($zipFile->getListFiles() as $name) {
  529. static::assertStringEndsWith('.md', $name);
  530. }
  531. $zipFile->close();
  532. }
  533. public function testDeleteFromGlobFailEmpty(): void
  534. {
  535. $this->expectException(InvalidArgumentException::class);
  536. $this->expectExceptionMessage('The glob pattern is not specified');
  537. $zipFile = new ZipFile();
  538. $zipFile->deleteFromGlob('');
  539. }
  540. /**
  541. * Delete entries from regex pattern.
  542. *
  543. * @throws ZipException
  544. */
  545. public function testDeleteFromRegex(): void
  546. {
  547. $inputDir = \dirname(__DIR__);
  548. $zipFile = new ZipFile();
  549. $zipFile->addFilesFromRegexRecursive($inputDir, '~\.(xml|json)$~i', 'Path');
  550. $zipFile->saveAsFile($this->outputFilename);
  551. $zipFile->close();
  552. static::assertCorrectZipArchive($this->outputFilename);
  553. $zipFile->openFile($this->outputFilename);
  554. $zipFile->deleteFromRegex('~\.(json)$~i');
  555. $zipFile->addFromString('test.txt', 'content');
  556. $zipFile->deleteFromRegex('~\.txt$~');
  557. $zipFile->saveAsFile($this->outputFilename);
  558. $zipFile->close();
  559. static::assertCorrectZipArchive($this->outputFilename);
  560. $zipFile->openFile($this->outputFilename);
  561. static::assertFalse(isset($zipFile['Path/composer.json']));
  562. static::assertFalse(isset($zipFile['Path/test.txt']));
  563. static::assertTrue(isset($zipFile['Path/phpunit.xml']));
  564. $zipFile->close();
  565. }
  566. public function testDeleteFromRegexFailEmpty(): void
  567. {
  568. $this->expectException(InvalidArgumentException::class);
  569. $this->expectExceptionMessage('The regex pattern is not specified');
  570. $zipFile = new ZipFile();
  571. $zipFile->deleteFromRegex('');
  572. }
  573. /**
  574. * Delete all entries.
  575. *
  576. * @throws ZipException
  577. */
  578. public function testDeleteAll(): void
  579. {
  580. $zipFile = new ZipFile();
  581. $zipFile->addDirRecursive(\dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'src');
  582. static::assertTrue($zipFile->count() > 0);
  583. $zipFile->saveAsFile($this->outputFilename);
  584. $zipFile->close();
  585. static::assertCorrectZipArchive($this->outputFilename);
  586. $zipFile->openFile($this->outputFilename);
  587. static::assertTrue($zipFile->count() > 0);
  588. $zipFile->deleteAll();
  589. $zipFile->saveAsFile($this->outputFilename);
  590. $zipFile->close();
  591. static::assertCorrectEmptyZip($this->outputFilename);
  592. $zipFile->openFile($this->outputFilename);
  593. static::assertSame($zipFile->count(), 0);
  594. $zipFile->close();
  595. }
  596. /**
  597. * Test zip archive comment.
  598. *
  599. * @throws ZipException
  600. */
  601. public function testArchiveComment(): void
  602. {
  603. $comment = 'This zip file comment' . \PHP_EOL
  604. . 'Αυτό το σχόλιο αρχείο zip' . \PHP_EOL
  605. . 'Это комментарий zip архива' . \PHP_EOL
  606. . '這個ZIP文件註釋' . \PHP_EOL
  607. . 'ეს zip ფაილის კომენტარი' . \PHP_EOL
  608. . 'このzipファイルにコメント' . \PHP_EOL
  609. . 'ความคิดเห็นนี้ไฟล์ซิป';
  610. $zipFile = new ZipFile();
  611. $zipFile->setArchiveComment($comment);
  612. $zipFile->addFile(__FILE__);
  613. $zipFile->saveAsFile($this->outputFilename);
  614. $zipFile->close();
  615. static::assertCorrectZipArchive($this->outputFilename);
  616. $zipFile->openFile($this->outputFilename);
  617. static::assertSame($zipFile->getArchiveComment(), $comment);
  618. $zipFile->setArchiveComment(/* null */); // remove archive comment
  619. $zipFile->saveAsFile($this->outputFilename);
  620. $zipFile->close();
  621. static::assertCorrectZipArchive($this->outputFilename);
  622. // check empty comment
  623. $zipFile->openFile($this->outputFilename);
  624. static::assertNull($zipFile->getArchiveComment());
  625. $zipFile->close();
  626. }
  627. /**
  628. * Test very long archive comment.
  629. */
  630. public function testVeryLongArchiveComment(): void
  631. {
  632. $this->expectException(InvalidArgumentException::class);
  633. $comment = 'Very long comment' . \PHP_EOL
  634. . 'Очень длинный комментарий' . \PHP_EOL;
  635. $comment = str_repeat($comment, (int) ceil(0xFFFF / \strlen($comment)) + \strlen($comment) + 1);
  636. $zipFile = new ZipFile();
  637. $zipFile->setArchiveComment($comment);
  638. }
  639. /**
  640. * Test zip entry comment.
  641. *
  642. * @throws ZipException
  643. * @throws \Exception
  644. */
  645. public function testEntryComment(): void
  646. {
  647. $entries = [
  648. '文件1.txt' => [
  649. 'data' => random_bytes(255),
  650. 'comment' => '這是註釋的條目。',
  651. ],
  652. 'file2.txt' => [
  653. 'data' => random_bytes(255),
  654. 'comment' => null,
  655. ],
  656. 'file3.txt' => [
  657. 'data' => random_bytes(255),
  658. 'comment' => random_bytes(255),
  659. ],
  660. 'file4.txt' => [
  661. 'data' => random_bytes(255),
  662. 'comment' => 'Комментарий файла',
  663. ],
  664. 'file5.txt' => [
  665. 'data' => random_bytes(255),
  666. 'comment' => 'ไฟล์แสดงความคิดเห็น',
  667. ],
  668. 'file6 emoji 🙍🏼.txt' => [
  669. 'data' => random_bytes(255),
  670. 'comment' => 'Emoji comment file - 😀 ⛈ ❤️ 🤴🏽',
  671. ],
  672. ];
  673. // create archive with entry comments
  674. $zipFile = new ZipFile();
  675. foreach ($entries as $entryName => $item) {
  676. $zipFile->addFromString($entryName, $item['data']);
  677. $zipFile->setEntryComment($entryName, $item['comment']);
  678. }
  679. $zipFile->saveAsFile($this->outputFilename);
  680. $zipFile->close();
  681. static::assertCorrectZipArchive($this->outputFilename);
  682. // check and modify comments
  683. $zipFile->openFile($this->outputFilename);
  684. foreach ($zipFile->getListFiles() as $entryName) {
  685. $entriesItem = $entries[$entryName];
  686. static::assertNotEmpty($entriesItem);
  687. static::assertSame($zipFile[$entryName], $entriesItem['data']);
  688. static::assertSame($zipFile->getEntryComment($entryName), (string) $entriesItem['comment']);
  689. }
  690. // modify comment
  691. $entries['file5.txt']['comment'] = random_bytes(256);
  692. $zipFile->setEntryComment('file5.txt', $entries['file5.txt']['comment']);
  693. $zipFile->saveAsFile($this->outputFilename);
  694. $zipFile->close();
  695. static::assertCorrectZipArchive($this->outputFilename);
  696. // check modify comments
  697. $zipFile->openFile($this->outputFilename);
  698. foreach ($entries as $entryName => $entriesItem) {
  699. static::assertTrue(isset($zipFile[$entryName]));
  700. static::assertSame($zipFile->getEntryComment($entryName), (string) $entriesItem['comment']);
  701. static::assertSame($zipFile[$entryName], $entriesItem['data']);
  702. }
  703. $zipFile->close();
  704. }
  705. /**
  706. * Test zip entry very long comment.
  707. *
  708. * @throws ZipException
  709. */
  710. public function testVeryLongEntryComment(): void
  711. {
  712. $this->expectException(InvalidArgumentException::class);
  713. $this->expectExceptionMessage('Comment too long');
  714. $comment = 'Very long comment' . \PHP_EOL
  715. . 'Очень длинный комментарий' . \PHP_EOL;
  716. $comment = str_repeat($comment, (int) ceil(0xFFFF / \strlen($comment)) + \strlen($comment) + 1);
  717. $zipFile = new ZipFile();
  718. $zipFile->addFile(__FILE__, 'test');
  719. $zipFile->setEntryComment('test', $comment);
  720. }
  721. /**
  722. * @throws ZipException
  723. */
  724. public function testSetEntryCommentNotFoundEntry(): void
  725. {
  726. $this->expectException(ZipEntryNotFoundException::class);
  727. $zipFile = new ZipFile();
  728. $zipFile->setEntryComment('test', 'comment');
  729. }
  730. /**
  731. * Test all available support compression methods.
  732. *
  733. * @throws ZipException
  734. * @throws \Exception
  735. */
  736. public function testCompressionMethod(): void
  737. {
  738. $entries = [
  739. 1 => [
  740. 'data' => random_bytes(255),
  741. 'method' => ZipCompressionMethod::STORED,
  742. ],
  743. 2 => [
  744. 'data' => random_bytes(255),
  745. 'method' => ZipCompressionMethod::DEFLATED,
  746. ],
  747. ];
  748. if (\extension_loaded('bz2')) {
  749. $entries[3] = [
  750. 'data' => random_bytes(255),
  751. 'method' => ZipCompressionMethod::BZIP2,
  752. ];
  753. }
  754. $zipFile = new ZipFile();
  755. foreach ($entries as $entryName => $item) {
  756. $entryName = (string) $entryName;
  757. $zipFile->addFromString($entryName, $item['data'], $item['method']);
  758. }
  759. $zipFile->saveAsFile($this->outputFilename);
  760. $zipFile->close();
  761. static::assertCorrectZipArchive($this->outputFilename);
  762. $zipFile->openFile($this->outputFilename);
  763. $zipFile->setCompressionLevel(ZipCompressionLevel::MAXIMUM);
  764. foreach ($zipFile->getEntries() as $entryName => $zipEntry) {
  765. $entryName = (string) $entryName;
  766. static::assertSame($zipFile[$entryName], $entries[$entryName]['data']);
  767. static::assertSame($zipEntry->getCompressionMethod(), $entries[$entryName]['method']);
  768. }
  769. $zipFile->close();
  770. }
  771. /**
  772. * @dataProvider provideInvalidCompressionLevels
  773. */
  774. public function testSetInvalidCompressionLevel(int $compressionLevel): void
  775. {
  776. $this->expectException(InvalidArgumentException::class);
  777. $this->expectExceptionMessage('Invalid compression level. Minimum level 1. Maximum level 9');
  778. $zipFile = new ZipFile();
  779. $zipFile['file 1'] = 'contents';
  780. $zipFile->setCompressionLevel($compressionLevel);
  781. }
  782. public function provideInvalidCompressionLevels(): array
  783. {
  784. return [
  785. [-10],
  786. [-2],
  787. [10],
  788. [0xFFFF],
  789. ];
  790. }
  791. /**
  792. * Test extract all files.
  793. *
  794. * @throws ZipException
  795. * @throws \Exception
  796. */
  797. public function testExtract(): void
  798. {
  799. $entries = [
  800. 'test1.txt' => random_bytes(255),
  801. 'test2.txt' => random_bytes(255),
  802. 'test/test 2/test3.txt' => random_bytes(255),
  803. 'test empty/dir/' => null,
  804. ];
  805. $zipFile = new ZipFile();
  806. foreach ($entries as $entryName => $contents) {
  807. if ($contents === null) {
  808. $zipFile->addEmptyDir($entryName);
  809. } else {
  810. $zipFile->addFromString($entryName, $contents);
  811. }
  812. }
  813. $zipFile->saveAsFile($this->outputFilename);
  814. $zipFile->close();
  815. static::assertTrue(mkdir($this->outputDirname, 0755, true));
  816. $zipFile->openFile($this->outputFilename);
  817. $zipFile->extractTo($this->outputDirname, null, [], $extractedEntries);
  818. foreach ($entries as $entryName => $contents) {
  819. $name = $entryName;
  820. if (\DIRECTORY_SEPARATOR === '\\') {
  821. $name = str_replace('/', '\\', $name);
  822. }
  823. $fullExtractedFilename = $this->outputDirname . \DIRECTORY_SEPARATOR . $name;
  824. static::assertTrue(
  825. isset($extractedEntries[$fullExtractedFilename]),
  826. 'No extract info for ' . $fullExtractedFilename
  827. );
  828. if ($contents === null) {
  829. static::assertDirectoryExists($fullExtractedFilename);
  830. static::assertTrue(FilesUtil::isEmptyDir($fullExtractedFilename));
  831. } else {
  832. static::assertTrue(is_file($fullExtractedFilename));
  833. $contents = file_get_contents($fullExtractedFilename);
  834. static::assertSame($contents, $contents);
  835. }
  836. /** @var ZipEntry $entry */
  837. $entry = $extractedEntries[$fullExtractedFilename];
  838. static::assertSame($entry->getName(), $entryName);
  839. }
  840. $zipFile->close();
  841. }
  842. /**
  843. * Test extract some files.
  844. *
  845. * @throws ZipException
  846. * @throws \Exception
  847. */
  848. public function testExtractSomeFiles(): void
  849. {
  850. $entries = [
  851. 'test1.txt' => random_bytes(255),
  852. 'test2.txt' => random_bytes(255),
  853. 'test3.txt' => random_bytes(255),
  854. 'test4.txt' => random_bytes(255),
  855. 'test5.txt' => random_bytes(255),
  856. 'test/test/test.txt' => random_bytes(255),
  857. 'test/test/test 2.txt' => random_bytes(255),
  858. 'test empty/dir/' => null,
  859. 'test empty/dir2/' => null,
  860. ];
  861. $extractEntries = [
  862. 'test1.txt',
  863. 'test3.txt',
  864. 'test5.txt',
  865. 'test/test/test 2.txt',
  866. 'test empty/dir2/',
  867. ];
  868. static::assertTrue(mkdir($this->outputDirname, 0755, true));
  869. $zipFile = new ZipFile();
  870. $zipFile->addAll($entries);
  871. $zipFile->saveAsFile($this->outputFilename);
  872. $zipFile->close();
  873. $zipFile->openFile($this->outputFilename);
  874. $zipFile->extractTo($this->outputDirname, $extractEntries);
  875. foreach ($entries as $entryName => $value) {
  876. $fullExtractFilename = $this->outputDirname . \DIRECTORY_SEPARATOR . $entryName;
  877. if (\in_array($entryName, $extractEntries, true)) {
  878. if ($value === null) {
  879. static::assertDirectoryExists($fullExtractFilename);
  880. static::assertTrue(FilesUtil::isEmptyDir($fullExtractFilename));
  881. } else {
  882. static::assertTrue(is_file($fullExtractFilename));
  883. $contents = file_get_contents($fullExtractFilename);
  884. static::assertEquals($contents, $value);
  885. }
  886. } elseif ($value === null) {
  887. static::assertDirectoryDoesNotExist($fullExtractFilename);
  888. } else {
  889. static::assertFalse(is_file($fullExtractFilename));
  890. }
  891. }
  892. static::assertFalse(is_file($this->outputDirname . \DIRECTORY_SEPARATOR . 'test/test/test.txt'));
  893. $zipFile->extractTo($this->outputDirname, 'test/test/test.txt');
  894. static::assertTrue(is_file($this->outputDirname . \DIRECTORY_SEPARATOR . 'test/test/test.txt'));
  895. $zipFile->close();
  896. }
  897. /**
  898. * @throws ZipException
  899. */
  900. public function testExtractFail(): void
  901. {
  902. $this->expectException(ZipException::class);
  903. $this->expectExceptionMessage('not found');
  904. $zipFile = new ZipFile();
  905. $zipFile['file'] = 'content';
  906. $zipFile->saveAsFile($this->outputFilename);
  907. $zipFile->close();
  908. $zipFile->openFile($this->outputFilename);
  909. $zipFile->extractTo('path/to/path');
  910. }
  911. /**
  912. * @throws ZipException
  913. */
  914. public function testExtractFail2(): void
  915. {
  916. $this->expectException(ZipException::class);
  917. $this->expectExceptionMessage('Destination is not a directory');
  918. $zipFile = new ZipFile();
  919. $zipFile['file'] = 'content';
  920. $zipFile->saveAsFile($this->outputFilename);
  921. $zipFile->close();
  922. $zipFile->openFile($this->outputFilename);
  923. $zipFile->extractTo($this->outputFilename);
  924. }
  925. /**
  926. * @throws ZipException
  927. */
  928. public function testExtractFail3(): void
  929. {
  930. $this->expectException(ZipException::class);
  931. $this->expectExceptionMessage('Destination is not a writable directory');
  932. static::skipTestForRootUser();
  933. $zipFile = new ZipFile();
  934. $zipFile['file'] = 'content';
  935. $zipFile->saveAsFile($this->outputFilename);
  936. $zipFile->close();
  937. static::assertTrue(mkdir($this->outputDirname, 0444, true));
  938. static::assertTrue(chmod($this->outputDirname, 0444));
  939. $zipFile->openFile($this->outputFilename);
  940. $zipFile->extractTo($this->outputDirname);
  941. }
  942. /**
  943. * @noinspection OnlyWritesOnParameterInspection
  944. */
  945. public function testAddFromArrayAccessNullName(): void
  946. {
  947. $this->expectException(InvalidArgumentException::class);
  948. $this->expectExceptionMessage('Key must not be null, but must contain the name of the zip entry.');
  949. $zipFile = new ZipFile();
  950. $zipFile[null] = 'content';
  951. }
  952. /**
  953. * @noinspection OnlyWritesOnParameterInspection
  954. */
  955. public function testAddFromArrayAccessEmptyName(): void
  956. {
  957. $this->expectException(InvalidArgumentException::class);
  958. $this->expectExceptionMessage('Key is empty, but must contain the name of the zip entry.');
  959. $zipFile = new ZipFile();
  960. $zipFile[''] = 'content';
  961. }
  962. /**
  963. * @throws ZipException
  964. */
  965. public function testAddFromStringUnsupportedMethod(): void
  966. {
  967. $this->expectException(ZipUnsupportMethodException::class);
  968. $this->expectExceptionMessage('Compression method 99 (AES Encryption) is not supported.');
  969. $zipFile = new ZipFile();
  970. $zipFile->addFromString('file', 'contents', ZipCompressionMethod::WINZIP_AES);
  971. $zipFile->outputAsString();
  972. }
  973. /**
  974. * @throws ZipException
  975. */
  976. public function testAddFromStringEmptyEntryName(): void
  977. {
  978. $this->expectException(InvalidArgumentException::class);
  979. $this->expectExceptionMessage('Empty entry name');
  980. $zipFile = new ZipFile();
  981. $zipFile->addFromString('', 'contents');
  982. }
  983. /**
  984. * Test compression method from add string.
  985. *
  986. * @throws ZipException
  987. */
  988. public function testAddFromStringCompressionMethod(): void
  989. {
  990. $fileStored = sys_get_temp_dir() . '/zip-stored.txt';
  991. $fileDeflated = sys_get_temp_dir() . '/zip-deflated.txt';
  992. static::assertNotFalse(file_put_contents($fileStored, 'content'));
  993. static::assertNotFalse(file_put_contents($fileDeflated, str_repeat('content', 200)));
  994. $zipFile = new ZipFile();
  995. $zipFile->addFromString(basename($fileStored), file_get_contents($fileStored));
  996. $zipFile->addFromString(basename($fileDeflated), file_get_contents($fileDeflated));
  997. $zipFile->saveAsFile($this->outputFilename);
  998. $zipFile->close();
  999. unlink($fileStored);
  1000. unlink($fileDeflated);
  1001. $zipFile->openFile($this->outputFilename);
  1002. $methodStored = $zipFile->getEntry(basename($fileStored))->getCompressionMethod();
  1003. $methodDeflated = $zipFile->getEntry(basename($fileDeflated))->getCompressionMethod();
  1004. static::assertSame($methodStored, ZipCompressionMethod::STORED);
  1005. static::assertSame($methodDeflated, ZipCompressionMethod::DEFLATED);
  1006. $zipFile->close();
  1007. }
  1008. /**
  1009. * @throws ZipException
  1010. */
  1011. public function testAddFromStreamInvalidResource(): void
  1012. {
  1013. $this->expectException(InvalidArgumentException::class);
  1014. $this->expectExceptionMessage('Stream is not a resource');
  1015. $zipFile = new ZipFile();
  1016. /** @noinspection PhpParamsInspection */
  1017. $zipFile->addFromStream('invalid resource', 'name');
  1018. }
  1019. /**
  1020. * @throws ZipException
  1021. */
  1022. public function testAddFromStreamEmptyEntryName(): void
  1023. {
  1024. $this->expectException(InvalidArgumentException::class);
  1025. $this->expectExceptionMessage('Empty entry name');
  1026. $handle = fopen(__FILE__, 'rb');
  1027. $zipFile = new ZipFile();
  1028. $zipFile->addFromStream($handle, '');
  1029. }
  1030. /**
  1031. * @throws ZipException
  1032. */
  1033. public function testAddFromStreamUnsupportedMethod(): void
  1034. {
  1035. $this->expectException(ZipUnsupportMethodException::class);
  1036. $this->expectExceptionMessage('Compression method 99 (AES Encryption) is not supported.');
  1037. $handle = fopen(__FILE__, 'rb');
  1038. $zipFile = new ZipFile();
  1039. $zipFile->addFromStream($handle, basename(__FILE__), ZipCompressionMethod::WINZIP_AES);
  1040. $zipFile->outputAsString();
  1041. }
  1042. /**
  1043. * Test compression method from add stream.
  1044. *
  1045. * @throws ZipException
  1046. */
  1047. public function testAddFromStreamCompressionMethod(): void
  1048. {
  1049. $fileStored = sys_get_temp_dir() . '/zip-stored.txt';
  1050. $fileDeflated = sys_get_temp_dir() . '/zip-deflated.txt';
  1051. static::assertNotFalse(file_put_contents($fileStored, 'content'));
  1052. static::assertNotFalse(file_put_contents($fileDeflated, str_repeat('content', 200)));
  1053. $fpStored = fopen($fileStored, 'rb');
  1054. $fpDeflated = fopen($fileDeflated, 'rb');
  1055. $zipFile = new ZipFile();
  1056. $zipFile->addFromStream($fpStored, basename($fileStored));
  1057. $zipFile->addFromStream($fpDeflated, basename($fileDeflated));
  1058. $zipFile->saveAsFile($this->outputFilename);
  1059. $zipFile->close();
  1060. unlink($fileStored);
  1061. unlink($fileDeflated);
  1062. $zipFile->openFile($this->outputFilename);
  1063. $methodStored = $zipFile->getEntry(basename($fileStored))->getCompressionMethod();
  1064. $methodDeflated = $zipFile->getEntry(basename($fileDeflated))->getCompressionMethod();
  1065. static::assertSame($methodStored, ZipCompressionMethod::STORED);
  1066. static::assertSame($methodDeflated, ZipCompressionMethod::DEFLATED);
  1067. $zipFile->close();
  1068. }
  1069. /**
  1070. * @throws ZipException
  1071. */
  1072. public function testAddFileCantExists(): void
  1073. {
  1074. $this->expectException(InvalidArgumentException::class);
  1075. $this->expectExceptionMessage('File path/to/file is not readable');
  1076. $zipFile = new ZipFile();
  1077. $zipFile->addFile('path/to/file');
  1078. }
  1079. /**
  1080. * @throws ZipException
  1081. */
  1082. public function testAddFileUnsupportedMethod(): void
  1083. {
  1084. $this->expectException(ZipUnsupportMethodException::class);
  1085. $this->expectExceptionMessage('Compression method 99 (AES Encryption) is not supported.');
  1086. $zipFile = new ZipFile();
  1087. $zipFile->addFile(__FILE__, null, ZipCompressionMethod::WINZIP_AES);
  1088. $zipFile->outputAsString();
  1089. }
  1090. /**
  1091. * @throws ZipException
  1092. */
  1093. public function testAddFileCannotOpen(): void
  1094. {
  1095. static::skipTestForWindows();
  1096. static::skipTestForRootUser();
  1097. $this->expectException(InvalidArgumentException::class);
  1098. $this->expectExceptionMessage('is not readable');
  1099. static::assertNotFalse(file_put_contents($this->outputFilename, ''));
  1100. static::assertTrue(chmod($this->outputFilename, 0244));
  1101. $zipFile = new ZipFile();
  1102. $zipFile->addFile($this->outputFilename);
  1103. }
  1104. /**
  1105. * @throws ZipException
  1106. */
  1107. public function testAddDirEmptyDirname(): void
  1108. {
  1109. $this->expectException(InvalidArgumentException::class);
  1110. $this->expectExceptionMessage('The input directory is not specified');
  1111. $zipFile = new ZipFile();
  1112. $zipFile->addDir('');
  1113. }
  1114. /**
  1115. * @throws ZipException
  1116. */
  1117. public function testAddDirCantExists(): void
  1118. {
  1119. $this->expectException(InvalidArgumentException::class);
  1120. $this->expectExceptionMessage('does not exist');
  1121. $zipFile = new ZipFile();
  1122. $zipFile->addDir(uniqid('', false));
  1123. }
  1124. /**
  1125. * @throws ZipException
  1126. */
  1127. public function testAddDirRecursiveEmptyDirname(): void
  1128. {
  1129. $this->expectException(InvalidArgumentException::class);
  1130. $this->expectExceptionMessage('The input directory is not specified');
  1131. $zipFile = new ZipFile();
  1132. $zipFile->addDirRecursive('');
  1133. }
  1134. /**
  1135. * @throws ZipException
  1136. */
  1137. public function testAddDirRecursiveCantExists(): void
  1138. {
  1139. $this->expectException(InvalidArgumentException::class);
  1140. $this->expectExceptionMessage('does not exist');
  1141. $zipFile = new ZipFile();
  1142. $zipFile->addDirRecursive(uniqid('', false));
  1143. }
  1144. /**
  1145. * @throws ZipException
  1146. */
  1147. public function testAddFilesFromGlobEmpty(): void
  1148. {
  1149. $this->expectException(InvalidArgumentException::class);
  1150. $this->expectExceptionMessage('The input directory is not specified');
  1151. $zipFile = new ZipFile();
  1152. $zipFile->addFilesFromGlob('', '*.png');
  1153. }
  1154. /**
  1155. * @throws ZipException
  1156. */
  1157. public function testAddFilesFromGlobCantExists(): void
  1158. {
  1159. $this->expectException(InvalidArgumentException::class);
  1160. $this->expectExceptionMessage('does not exist');
  1161. $zipFile = new ZipFile();
  1162. $zipFile->addFilesFromGlob('path/to/path', '*.png');
  1163. }
  1164. /**
  1165. * @throws ZipException
  1166. */
  1167. public function testAddFilesFromGlobEmptyPattern(): void
  1168. {
  1169. $this->expectException(InvalidArgumentException::class);
  1170. $this->expectExceptionMessage('The glob pattern is not specified');
  1171. $zipFile = new ZipFile();
  1172. $zipFile->addFilesFromGlob(__DIR__, '');
  1173. }
  1174. /**
  1175. * @throws ZipException
  1176. */
  1177. public function testAddFilesFromGlobRecursiveEmpty(): void
  1178. {
  1179. $this->expectException(InvalidArgumentException::class);
  1180. $this->expectExceptionMessage('The input directory is not specified');
  1181. $zipFile = new ZipFile();
  1182. $zipFile->addFilesFromGlobRecursive('', '*.png');
  1183. }
  1184. /**
  1185. * @throws ZipException
  1186. */
  1187. public function testAddFilesFromGlobRecursiveCantExists(): void
  1188. {
  1189. $this->expectException(InvalidArgumentException::class);
  1190. $this->expectExceptionMessage('does not exist');
  1191. $zipFile = new ZipFile();
  1192. $zipFile->addFilesFromGlobRecursive('path/to/path', '*.png');
  1193. }
  1194. /**
  1195. * @throws ZipException
  1196. */
  1197. public function testAddFilesFromGlobRecursiveEmptyPattern(): void
  1198. {
  1199. $this->expectException(InvalidArgumentException::class);
  1200. $this->expectExceptionMessage('The glob pattern is not specified');
  1201. $zipFile = new ZipFile();
  1202. $zipFile->addFilesFromGlobRecursive(__DIR__, '');
  1203. }
  1204. /**
  1205. * @throws ZipException
  1206. */
  1207. public function testAddFilesFromRegexDirectoryEmpty(): void
  1208. {
  1209. $this->expectException(InvalidArgumentException::class);
  1210. $this->expectExceptionMessage('The input directory is not specified');
  1211. $zipFile = new ZipFile();
  1212. $zipFile->addFilesFromRegex('', '~\.png$~i');
  1213. }
  1214. /**
  1215. * @throws ZipException
  1216. */
  1217. public function testAddFilesFromRegexCantExists(): void
  1218. {
  1219. $this->expectException(InvalidArgumentException::class);
  1220. $this->expectExceptionMessage('does not exist');
  1221. $zipFile = new ZipFile();
  1222. $zipFile->addFilesFromRegex('path/to/path', '~\.png$~i');
  1223. }
  1224. /**
  1225. * @throws ZipException
  1226. */
  1227. public function testAddFilesFromRegexEmptyPattern(): void
  1228. {
  1229. $this->expectException(InvalidArgumentException::class);
  1230. $this->expectExceptionMessage('The regex pattern is not specified');
  1231. $zipFile = new ZipFile();
  1232. $zipFile->addFilesFromRegex(__DIR__, '');
  1233. }
  1234. /**
  1235. * @throws ZipException
  1236. */
  1237. public function testAddFilesFromRegexRecursiveEmpty(): void
  1238. {
  1239. $this->expectException(InvalidArgumentException::class);
  1240. $this->expectExceptionMessage('The input directory is not specified');
  1241. $zipFile = new ZipFile();
  1242. $zipFile->addFilesFromRegexRecursive('', '~\.png$~i');
  1243. }
  1244. /**
  1245. * @throws ZipException
  1246. */
  1247. public function testAddFilesFromRegexRecursiveCantExists(): void
  1248. {
  1249. $this->expectException(InvalidArgumentException::class);
  1250. $this->expectExceptionMessage('does not exist');
  1251. $zipFile = new ZipFile();
  1252. $zipFile->addFilesFromGlobRecursive('path/to/path', '~\.png$~i');
  1253. }
  1254. /**
  1255. * @throws ZipException
  1256. */
  1257. public function testAddFilesFromRegexRecursiveEmptyPattern(): void
  1258. {
  1259. $this->expectException(InvalidArgumentException::class);
  1260. $this->expectExceptionMessage('The regex pattern is not specified');
  1261. $zipFile = new ZipFile();
  1262. $zipFile->addFilesFromRegexRecursive(__DIR__, '');
  1263. }
  1264. /**
  1265. * @throws ZipException
  1266. */
  1267. public function testSaveAsStreamBadStream(): void
  1268. {
  1269. $this->expectException(InvalidArgumentException::class);
  1270. $this->expectExceptionMessage('handle is not a resource');
  1271. $zipFile = new ZipFile();
  1272. /** @noinspection PhpParamsInspection */
  1273. $zipFile->saveAsStream('bad stream');
  1274. }
  1275. /**
  1276. * @throws ZipException
  1277. */
  1278. public function testSaveAsFileNotWritable(): void
  1279. {
  1280. static::skipTestForWindows();
  1281. static::skipTestForRootUser();
  1282. static::assertTrue(mkdir($this->outputDirname, 0444, true));
  1283. static::assertTrue(chmod($this->outputDirname, 0444));
  1284. $this->outputFilename = $this->outputDirname . \DIRECTORY_SEPARATOR . basename($this->outputFilename);
  1285. $this->expectException(InvalidArgumentException::class);
  1286. $this->expectExceptionMessage('Permission denied');
  1287. $zipFile = new ZipFile();
  1288. $zipFile->saveAsFile($this->outputFilename);
  1289. }
  1290. /**
  1291. * Test `ZipFile` implemented \ArrayAccess, \Countable and |iterator.
  1292. *
  1293. * @throws ZipException
  1294. * @throws \Exception
  1295. */
  1296. public function testZipFileArrayAccessAndCountableAndIterator(): void
  1297. {
  1298. $files = [];
  1299. $numFiles = random_int(20, 100);
  1300. for ($i = 0; $i < $numFiles; $i++) {
  1301. $files['file' . $i . '.txt'] = random_bytes(255);
  1302. }
  1303. $compressionMethods = [ZipCompressionMethod::STORED, ZipCompressionMethod::DEFLATED];
  1304. if (\extension_loaded('bz2')) {
  1305. $compressionMethods[] = ZipCompressionMethod::BZIP2;
  1306. }
  1307. $zipFile = new ZipFile();
  1308. $zipFile->setCompressionLevel(ZipCompressionLevel::SUPER_FAST);
  1309. $i = 0;
  1310. $countMethods = \count($compressionMethods);
  1311. foreach ($files as $entryName => $content) {
  1312. $compressionMethod = $compressionMethods[$i++ % $countMethods];
  1313. $zipFile->addFromString($entryName, $content, $compressionMethod);
  1314. }
  1315. $zipFile->saveAsFile($this->outputFilename);
  1316. $zipFile->close();
  1317. static::assertCorrectZipArchive($this->outputFilename);
  1318. $zipFile->openFile($this->outputFilename);
  1319. // Test \Countable
  1320. static::assertSame($zipFile->count(), $numFiles);
  1321. static::assertSame(\count($zipFile), $numFiles);
  1322. // Test \ArrayAccess
  1323. reset($files);
  1324. foreach ($zipFile as $entryName => $content) {
  1325. static::assertSame($entryName, key($files));
  1326. static::assertSame($content, current($files));
  1327. next($files);
  1328. }
  1329. // Test \Iterator
  1330. reset($files);
  1331. $iterator = new \ArrayIterator(iterator_to_array($zipFile));
  1332. $iterator->rewind();
  1333. while ($iterator->valid()) {
  1334. $key = $iterator->key();
  1335. $value = $iterator->current();
  1336. static::assertSame($key, key($files));
  1337. static::assertSame($value, current($files));
  1338. next($files);
  1339. $iterator->next();
  1340. }
  1341. $zipFile->close();
  1342. $zipFile = new ZipFile();
  1343. $zipFile['file1.txt'] = 'content 1';
  1344. $zipFile['dir/file2.txt'] = 'content 1';
  1345. $zipFile['dir/empty dir/'] = null;
  1346. $zipFile->saveAsFile($this->outputFilename);
  1347. $zipFile->close();
  1348. static::assertCorrectZipArchive($this->outputFilename);
  1349. $zipFile->openFile($this->outputFilename);
  1350. static::assertTrue(isset($zipFile['file1.txt']));
  1351. static::assertTrue(isset($zipFile['dir/file2.txt']));
  1352. static::assertTrue(isset($zipFile['dir/empty dir/']));
  1353. static::assertFalse(isset($zipFile['dir/empty dir/2/']));
  1354. $zipFile['dir/empty dir/2/'] = null;
  1355. unset($zipFile['dir/file2.txt'], $zipFile['dir/empty dir/']);
  1356. $zipFile->saveAsFile($this->outputFilename);
  1357. $zipFile->close();
  1358. static::assertCorrectZipArchive($this->outputFilename);
  1359. $zipFile->openFile($this->outputFilename);
  1360. static::assertTrue(isset($zipFile['file1.txt']));
  1361. static::assertFalse(isset($zipFile['dir/file2.txt']));
  1362. static::assertFalse(isset($zipFile['dir/empty dir/']));
  1363. static::assertTrue(isset($zipFile['dir/empty dir/2/']));
  1364. $zipFile->close();
  1365. }
  1366. /**
  1367. * @throws ZipException
  1368. */
  1369. public function testArrayAccessAddFile(): void
  1370. {
  1371. $entryName = 'path/to/file.dat';
  1372. $entryNameStream = 'path/to/' . basename(__FILE__);
  1373. $zipFile = new ZipFile();
  1374. $zipFile[$entryName] = new \SplFileInfo(__FILE__);
  1375. $zipFile[$entryNameStream] = fopen(__FILE__, 'rb');
  1376. $zipFile->saveAsFile($this->outputFilename);
  1377. $zipFile->close();
  1378. static::assertCorrectZipArchive($this->outputFilename);
  1379. $zipFile->openFile($this->outputFilename);
  1380. static::assertSame(\count($zipFile), 2);
  1381. static::assertTrue(isset($zipFile[$entryName]));
  1382. static::assertTrue(isset($zipFile[$entryNameStream]));
  1383. static::assertSame($zipFile[$entryName], file_get_contents(__FILE__));
  1384. static::assertSame($zipFile[$entryNameStream], file_get_contents(__FILE__));
  1385. $zipFile->close();
  1386. }
  1387. /**
  1388. * @throws ZipException
  1389. * @throws \Exception
  1390. */
  1391. public function testUnknownCompressionMethod(): void
  1392. {
  1393. $zipFile = new ZipFile();
  1394. $zipFile->addFromString('file', 'content', ZipEntry::UNKNOWN);
  1395. $zipFile->addFromString('file2', base64_encode(random_bytes(512)), ZipEntry::UNKNOWN);
  1396. static::assertSame($zipFile->getEntry('file')->getCompressionMethod(), ZipCompressionMethod::STORED);
  1397. static::assertSame($zipFile->getEntry('file2')->getCompressionMethod(), ZipCompressionMethod::DEFLATED);
  1398. $zipFile->saveAsFile($this->outputFilename);
  1399. $zipFile->close();
  1400. $zipFile->openFile($this->outputFilename);
  1401. static::assertSame($zipFile->getEntry('file')->getCompressionMethod(), ZipCompressionMethod::STORED);
  1402. static::assertSame($zipFile->getEntry('file2')->getCompressionMethod(), ZipCompressionMethod::DEFLATED);
  1403. $zipFile->close();
  1404. }
  1405. /**
  1406. * @throws ZipException
  1407. */
  1408. public function testAddEmptyDirEmptyName(): void
  1409. {
  1410. $this->expectException(InvalidArgumentException::class);
  1411. $this->expectExceptionMessage('Empty entry name');
  1412. $zipFile = new ZipFile();
  1413. $zipFile->addEmptyDir('');
  1414. }
  1415. public function testNotFoundEntry(): void
  1416. {
  1417. $this->expectException(ZipEntryNotFoundException::class);
  1418. $this->expectExceptionMessage('"bad entry name"');
  1419. $zipFile = new ZipFile();
  1420. $zipFile['bad entry name'];
  1421. }
  1422. /**
  1423. * Test rewrite input file.
  1424. *
  1425. * @throws ZipException
  1426. */
  1427. public function testRewriteFile(): void
  1428. {
  1429. $zipFile = new ZipFile();
  1430. $zipFile['file'] = 'content';
  1431. $zipFile['file2'] = 'content2';
  1432. static::assertSame(\count($zipFile), 2);
  1433. $zipFile
  1434. ->saveAsFile($this->outputFilename)
  1435. ->close()
  1436. ;
  1437. $md5file = md5_file($this->outputFilename);
  1438. $zipFile->openFile($this->outputFilename);
  1439. static::assertSame(\count($zipFile), 2);
  1440. static::assertTrue(isset($zipFile['file']));
  1441. static::assertTrue(isset($zipFile['file2']));
  1442. $zipFile['file3'] = 'content3';
  1443. static::assertSame(\count($zipFile), 3);
  1444. $zipFile = $zipFile->rewrite();
  1445. static::assertSame(\count($zipFile), 3);
  1446. static::assertTrue(isset($zipFile['file']));
  1447. static::assertTrue(isset($zipFile['file2']));
  1448. static::assertTrue(isset($zipFile['file3']));
  1449. $zipFile->close();
  1450. static::assertNotSame(md5_file($this->outputFilename), $md5file);
  1451. }
  1452. /**
  1453. * Test rewrite for string.
  1454. *
  1455. * @throws ZipException
  1456. */
  1457. public function testRewriteString(): void
  1458. {
  1459. $this->expectException(ZipException::class);
  1460. $this->expectExceptionMessage('Overwrite is only supported for open local files');
  1461. $zipFile = new ZipFile();
  1462. $zipFile['file'] = 'content';
  1463. $zipFile['file2'] = 'content2';
  1464. $zipFile->saveAsFile($this->outputFilename);
  1465. $zipFile->close();
  1466. $zipFile->openFromString(file_get_contents($this->outputFilename));
  1467. static::assertSame(\count($zipFile), 2);
  1468. static::assertTrue(isset($zipFile['file']));
  1469. static::assertTrue(isset($zipFile['file2']));
  1470. $zipFile['file3'] = 'content3';
  1471. $zipFile = $zipFile->rewrite();
  1472. static::assertSame(\count($zipFile), 3);
  1473. static::assertTrue(isset($zipFile['file']));
  1474. static::assertTrue(isset($zipFile['file2']));
  1475. static::assertTrue(isset($zipFile['file3']));
  1476. $zipFile->close();
  1477. }
  1478. /**
  1479. * @throws ZipException
  1480. */
  1481. public function testRewriteNullStream(): void
  1482. {
  1483. $this->expectException(ZipException::class);
  1484. $this->expectExceptionMessage('input stream is null');
  1485. $zipFile = new ZipFile();
  1486. $zipFile->rewrite();
  1487. }
  1488. /**
  1489. * Checks the ability to overwrite an open zip file with a relative path.
  1490. *
  1491. * @throws ZipException
  1492. */
  1493. public function testRewriteRelativeFile(): void
  1494. {
  1495. $zipFile = new ZipFile();
  1496. $zipFile['entry.txt'] = 'test';
  1497. $zipFile->saveAsFile($this->outputFilename);
  1498. $zipFile->close();
  1499. $outputDirname = \dirname($this->outputFilename);
  1500. static::assertTrue(chdir($outputDirname));
  1501. $relativeFilename = basename($this->outputFilename);
  1502. $zipFile->openFile($this->outputFilename);
  1503. $zipFile['entry2.txt'] = 'test';
  1504. $zipFile->saveAsFile($relativeFilename);
  1505. $zipFile->close();
  1506. self::assertCorrectZipArchive($this->outputFilename);
  1507. }
  1508. /**
  1509. * Checks the ability to overwrite an open zip file with a relative path.
  1510. *
  1511. * @throws ZipException
  1512. */
  1513. public function testRewriteDifferentWinDirectorySeparator(): void
  1514. {
  1515. if (\DIRECTORY_SEPARATOR !== '\\') {
  1516. static::markTestSkipped('Windows test only');
  1517. }
  1518. $zipFile = new ZipFile();
  1519. $zipFile['entry.txt'] = 'test';
  1520. $zipFile->saveAsFile($this->outputFilename);
  1521. $zipFile->close();
  1522. $alternativeOutputFilename = str_replace('\\', '/', $this->outputFilename);
  1523. self::assertCorrectZipArchive($alternativeOutputFilename);
  1524. $zipFile->openFile($this->outputFilename);
  1525. $zipFile['entry2.txt'] = 'test';
  1526. $zipFile->saveAsFile($alternativeOutputFilename);
  1527. $zipFile->close();
  1528. self::assertCorrectZipArchive($alternativeOutputFilename);
  1529. $zipFile->openFile($this->outputFilename);
  1530. static::assertCount(2, $zipFile);
  1531. $zipFile->close();
  1532. }
  1533. /**
  1534. * @throws ZipException
  1535. */
  1536. public function testRewriteRelativeFile2(): void
  1537. {
  1538. $this->outputFilename = basename($this->outputFilename);
  1539. $zipFile = new ZipFile();
  1540. $zipFile['entry.txt'] = 'test';
  1541. $zipFile->saveAsFile($this->outputFilename);
  1542. $zipFile->close();
  1543. $absoluteOutputFilename = getcwd() . \DIRECTORY_SEPARATOR . $this->outputFilename;
  1544. self::assertCorrectZipArchive($absoluteOutputFilename);
  1545. $zipFile->openFile($this->outputFilename);
  1546. $zipFile['entry2.txt'] = 'test';
  1547. $zipFile->saveAsFile($absoluteOutputFilename);
  1548. $zipFile->close();
  1549. self::assertCorrectZipArchive($absoluteOutputFilename);
  1550. }
  1551. /**
  1552. * @throws ZipException
  1553. */
  1554. public function testFilename0(): void
  1555. {
  1556. $zipFile = new ZipFile();
  1557. $zipFile[0] = '0';
  1558. static::assertTrue(isset($zipFile['0']));
  1559. static::assertCount(1, $zipFile);
  1560. $zipFile
  1561. ->saveAsFile($this->outputFilename)
  1562. ->close()
  1563. ;
  1564. static::assertCorrectZipArchive($this->outputFilename);
  1565. $zipFile->openFile($this->outputFilename);
  1566. static::assertTrue(isset($zipFile[0]));
  1567. static::assertTrue(isset($zipFile['0']));
  1568. static::assertSame($zipFile['0'], '0');
  1569. static::assertCount(1, $zipFile);
  1570. $zipFile->close();
  1571. static::assertTrue(unlink($this->outputFilename));
  1572. $zipFile = new ZipFile();
  1573. $zipFile->addFromString('0', '0');
  1574. static::assertTrue(isset($zipFile[0]));
  1575. static::assertTrue(isset($zipFile['0']));
  1576. static::assertCount(1, $zipFile);
  1577. $zipFile
  1578. ->saveAsFile($this->outputFilename)
  1579. ->close()
  1580. ;
  1581. static::assertCorrectZipArchive($this->outputFilename);
  1582. }
  1583. /**
  1584. * @throws ZipException
  1585. */
  1586. public function testOutputAsPsr7Response(): void
  1587. {
  1588. $zipFile = new ZipFile();
  1589. for ($i = 0; $i < 10; $i++) {
  1590. $zipFile[$i] = (string) $i;
  1591. }
  1592. $filename = 'file.jar';
  1593. $response = $zipFile->outputAsPsr7Response(new Response(), $filename);
  1594. static::assertSame('application/java-archive', $response->getHeaderLine('content-type'));
  1595. static::assertSame('attachment; filename="file.jar"', $response->getHeaderLine('content-disposition'));
  1596. }
  1597. /**
  1598. * @throws ZipException
  1599. */
  1600. public function testOutputAsSymfonyResponse(): void
  1601. {
  1602. $zipFile = new ZipFile();
  1603. for ($i = 0; $i < 10; $i++) {
  1604. $zipFile[$i] = (string) $i;
  1605. }
  1606. $filename = 'file.jar';
  1607. $response = $zipFile->outputAsSymfonyResponse($filename);
  1608. static::assertSame('application/java-archive', $response->headers->get('content-type'));
  1609. static::assertSame('attachment; filename="file.jar"', $response->headers->get('content-disposition'));
  1610. }
  1611. /**
  1612. * @dataProvider provideCompressionLevels
  1613. *
  1614. * @throws ZipEntryNotFoundException
  1615. * @throws ZipException
  1616. * @throws \Exception
  1617. */
  1618. public function testCompressionLevel(int $compressionLevel): void
  1619. {
  1620. $fileContent = random_bytes(512);
  1621. $entryName = 'file.txt';
  1622. $zipFile = new ZipFile();
  1623. $zipFile
  1624. ->addFromString($entryName, $fileContent, ZipCompressionMethod::DEFLATED)
  1625. ->setCompressionLevelEntry($entryName, $compressionLevel)
  1626. ->saveAsFile($this->outputFilename)
  1627. ->close()
  1628. ;
  1629. static::assertCorrectZipArchive($this->outputFilename);
  1630. $zipFile->openFile($this->outputFilename);
  1631. static::assertSame($zipFile->getEntryContents($entryName), $fileContent);
  1632. static::assertSame($zipFile->getEntry($entryName)->getCompressionLevel(), $compressionLevel);
  1633. $zipFile->close();
  1634. }
  1635. public function provideCompressionLevels(): array
  1636. {
  1637. return [
  1638. [ZipCompressionLevel::MAXIMUM],
  1639. [ZipCompressionLevel::NORMAL],
  1640. [ZipCompressionLevel::FAST],
  1641. [ZipCompressionLevel::SUPER_FAST],
  1642. ];
  1643. }
  1644. /**
  1645. * @throws ZipException
  1646. */
  1647. public function testInvalidCompressionLevel(): void
  1648. {
  1649. $this->expectException(InvalidArgumentException::class);
  1650. $this->expectExceptionMessage('Invalid compression level');
  1651. $zipFile = new ZipFile();
  1652. $zipFile->addFromString('file', 'content');
  1653. $zipFile->setCompressionLevel(15);
  1654. }
  1655. /**
  1656. * @throws ZipException
  1657. */
  1658. public function testInvalidCompressionLevelEntry(): void
  1659. {
  1660. $this->expectException(InvalidArgumentException::class);
  1661. $this->expectExceptionMessage('Invalid compression level');
  1662. $zipFile = new ZipFile();
  1663. $zipFile->addFromString('file', 'content');
  1664. $zipFile->setCompressionLevelEntry('file', 15);
  1665. }
  1666. /**
  1667. * @throws ZipException
  1668. */
  1669. public function testCompressionGlobal(): void
  1670. {
  1671. $zipFile = new ZipFile();
  1672. for ($i = 0; $i < 10; $i++) {
  1673. $zipFile->addFromString('file' . $i, 'content', ZipCompressionMethod::DEFLATED);
  1674. }
  1675. $zipFile
  1676. ->setCompressionLevel(ZipCompressionLevel::SUPER_FAST)
  1677. ->saveAsFile($this->outputFilename)
  1678. ->close()
  1679. ;
  1680. static::assertCorrectZipArchive($this->outputFilename);
  1681. $zipFile->openFile($this->outputFilename);
  1682. $zipEntries = $zipFile->getEntries();
  1683. array_walk(
  1684. $zipEntries,
  1685. function (ZipEntry $zipEntry): void {
  1686. $this->assertSame($zipEntry->getCompressionLevel(), ZipCompressionLevel::SUPER_FAST);
  1687. }
  1688. );
  1689. $zipFile->close();
  1690. }
  1691. /**
  1692. * @throws ZipException
  1693. */
  1694. public function testCompressionMethodEntry(): void
  1695. {
  1696. $zipFile = new ZipFile();
  1697. $zipFile->addFromString('file', 'content', ZipCompressionMethod::STORED);
  1698. $zipFile->saveAsFile($this->outputFilename);
  1699. $zipFile->close();
  1700. $zipFile->openFile($this->outputFilename);
  1701. static::assertSame($zipFile->getEntry('file')->getCompressionMethod(), ZipCompressionMethod::STORED);
  1702. $zipFile->setCompressionMethodEntry('file', ZipCompressionMethod::DEFLATED);
  1703. static::assertSame($zipFile->getEntry('file')->getCompressionMethod(), ZipCompressionMethod::DEFLATED);
  1704. $zipFile->rewrite();
  1705. static::assertSame($zipFile->getEntry('file')->getCompressionMethod(), ZipCompressionMethod::DEFLATED);
  1706. }
  1707. /**
  1708. * @throws ZipException
  1709. */
  1710. public function testInvalidCompressionMethodEntry(): void
  1711. {
  1712. $this->expectException(ZipUnsupportMethodException::class);
  1713. $this->expectExceptionMessage('Compression method 99 (AES Encryption) is not supported.');
  1714. $zipFile = new ZipFile();
  1715. $zipFile->addFromString('file', 'content', ZipCompressionMethod::STORED);
  1716. $zipFile->setCompressionMethodEntry('file', 99);
  1717. $zipFile->outputAsString();
  1718. }
  1719. /**
  1720. * @throws ZipException
  1721. */
  1722. public function testUnchangeAll(): void
  1723. {
  1724. $zipFile = new ZipFile();
  1725. for ($i = 0; $i < 10; $i++) {
  1726. $zipFile[$i] = $i;
  1727. }
  1728. $zipFile->setArchiveComment('comment');
  1729. static::assertCount(10, $zipFile);
  1730. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1731. $zipFile->saveAsFile($this->outputFilename);
  1732. $zipFile->unchangeAll();
  1733. static::assertCount(0, $zipFile);
  1734. static::assertNull($zipFile->getArchiveComment());
  1735. $zipFile->close();
  1736. $zipFile->openFile($this->outputFilename);
  1737. static::assertCount(10, $zipFile);
  1738. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1739. for ($i = 10; $i < 100; $i++) {
  1740. $zipFile[$i] = $i;
  1741. }
  1742. $zipFile->setArchiveComment('comment 2');
  1743. static::assertCount(100, $zipFile);
  1744. static::assertSame($zipFile->getArchiveComment(), 'comment 2');
  1745. $zipFile->unchangeAll();
  1746. static::assertCount(10, $zipFile);
  1747. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1748. $zipFile->close();
  1749. }
  1750. /**
  1751. * @throws ZipException
  1752. */
  1753. public function testUnchangeArchiveComment(): void
  1754. {
  1755. $zipFile = new ZipFile();
  1756. for ($i = 0; $i < 10; $i++) {
  1757. $zipFile[$i] = $i;
  1758. }
  1759. $zipFile->setArchiveComment('comment');
  1760. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1761. $zipFile->saveAsFile($this->outputFilename);
  1762. $zipFile->unchangeArchiveComment();
  1763. static::assertNull($zipFile->getArchiveComment());
  1764. $zipFile->close();
  1765. $zipFile->openFile($this->outputFilename);
  1766. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1767. $zipFile->setArchiveComment('comment 2');
  1768. static::assertSame($zipFile->getArchiveComment(), 'comment 2');
  1769. $zipFile->unchangeArchiveComment();
  1770. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1771. $zipFile->close();
  1772. }
  1773. /**
  1774. * @throws ZipException
  1775. */
  1776. public function testUnchangeEntry(): void
  1777. {
  1778. $zipFile = new ZipFile();
  1779. $zipFile['file 1'] = 'content 1';
  1780. $zipFile['file 2'] = 'content 2';
  1781. $zipFile
  1782. ->saveAsFile($this->outputFilename)
  1783. ->close()
  1784. ;
  1785. $zipFile->openFile($this->outputFilename);
  1786. $zipFile['file 1'] = 'modify content 1';
  1787. $zipFile->setPasswordEntry('file 1', 'password');
  1788. static::assertSame($zipFile['file 1'], 'modify content 1');
  1789. static::assertTrue($zipFile->getEntry('file 1')->isEncrypted());
  1790. static::assertSame($zipFile['file 2'], 'content 2');
  1791. static::assertFalse($zipFile->getEntry('file 2')->isEncrypted());
  1792. $zipFile->unchangeEntry('file 1');
  1793. static::assertSame($zipFile['file 1'], 'content 1');
  1794. static::assertFalse($zipFile->getEntry('file 1')->isEncrypted());
  1795. static::assertSame($zipFile['file 2'], 'content 2');
  1796. static::assertFalse($zipFile->getEntry('file 2')->isEncrypted());
  1797. $zipFile->close();
  1798. }
  1799. /**
  1800. * @runInSeparateProcess
  1801. *
  1802. * @dataProvider provideOutputAsAttachment
  1803. *
  1804. * @throws ZipException
  1805. */
  1806. public function testOutputAsAttachment(string $zipFilename, ?string $mimeType, string $expectedMimeType, bool $attachment, string $expectedAttachment): void
  1807. {
  1808. $zipFile = new ZipFile();
  1809. $file1Contents = 'content 1';
  1810. $zipFile['file 1'] = $file1Contents;
  1811. ob_start();
  1812. $zipFile->outputAsAttachment($zipFilename, $mimeType, $attachment);
  1813. $zipContents = ob_get_clean();
  1814. $zipFile->close();
  1815. $length = \strlen($zipContents);
  1816. static::assertTrue($length > 0);
  1817. $zipFile->openFromString($zipContents);
  1818. static::assertSame($zipFile['file 1'], $file1Contents);
  1819. $zipFile->close();
  1820. if (\function_exists('xdebug_get_headers')) {
  1821. $expectedHeaders = [
  1822. 'Content-Disposition: ' . $expectedAttachment . '; filename="' . $zipFilename . '"',
  1823. 'Content-Type: ' . $expectedMimeType,
  1824. 'Content-Length: ' . $length,
  1825. ];
  1826. /** @noinspection ForgottenDebugOutputInspection */
  1827. /** @noinspection PhpComposerExtensionStubsInspection */
  1828. static::assertSame($expectedHeaders, xdebug_get_headers());
  1829. }
  1830. }
  1831. public function provideOutputAsAttachment(): array
  1832. {
  1833. return [
  1834. ['file.zip', null, 'application/zip', true, 'attachment'],
  1835. ['file.zip', 'application/x-zip', 'application/x-zip', false, 'inline'],
  1836. ['file.apk', null, 'application/vnd.android.package-archive', true, 'attachment'],
  1837. ];
  1838. }
  1839. /**
  1840. * @dataProvider provideGetEntryStream
  1841. *
  1842. * @throws ZipEntryNotFoundException
  1843. * @throws ZipException
  1844. */
  1845. public function testReopenEntryStream(ZipFile $zipFile, string $entryName, string $contents): void
  1846. {
  1847. for ($i = 0; $i < 2; $i++) {
  1848. $fp = $zipFile->getEntryStream($entryName);
  1849. static::assertIsResource($fp);
  1850. static::assertSame(stream_get_contents($fp), $contents);
  1851. fclose($fp);
  1852. }
  1853. $zipFile->close();
  1854. }
  1855. /**
  1856. * @throws \Exception
  1857. */
  1858. public function provideGetEntryStream(): array
  1859. {
  1860. $entryName = 'entry';
  1861. $contents = random_bytes(1024);
  1862. $zipFileSpl = new ZipFile();
  1863. $zipFileSpl->addSplFile(new \SplFileInfo(__FILE__), $entryName);
  1864. return [
  1865. [(new ZipFile())->addFromString($entryName, $contents), $entryName, $contents],
  1866. [(new ZipFile())->addFile(__FILE__, $entryName), $entryName, file_get_contents(__FILE__)],
  1867. [
  1868. (new ZipFile())->addFromStream(fopen(__FILE__, 'rb'), $entryName),
  1869. $entryName,
  1870. file_get_contents(__FILE__),
  1871. ],
  1872. [$zipFileSpl, $entryName, file_get_contents(__FILE__)],
  1873. ];
  1874. }
  1875. /**
  1876. * @throws ZipException
  1877. */
  1878. public function testGetEntries(): void
  1879. {
  1880. $zipFile = new ZipFile();
  1881. for ($i = 0; $i < 100; $i++) {
  1882. $zipFile->addFromString($i . '.txt', 'contents ' . $i);
  1883. }
  1884. $zipFile->saveAsFile($this->outputFilename);
  1885. $zipFile->close();
  1886. $zipFile->openFile($this->outputFilename);
  1887. $zipEntries = $zipFile->getEntries();
  1888. static::assertCount(100, $zipEntries);
  1889. foreach ($zipEntries as $zipEntry) {
  1890. static::assertInstanceOf(ZipEntry::class, $zipEntry);
  1891. static::assertNotSame($zipEntry->getDosTime(), 0);
  1892. $zipEntry->setDosTime(0);
  1893. $zipEntry->setCreatedOS(ZipPlatform::OS_DOS);
  1894. $zipEntry->setExtractedOS(ZipPlatform::OS_DOS);
  1895. $zipEntry->setInternalAttributes(1);
  1896. $zipEntry->setExternalAttributes(0);
  1897. }
  1898. $zipFile->rewrite();
  1899. self::assertCorrectZipArchive($this->outputFilename);
  1900. foreach ($zipFile->getEntries() as $zipEntry) {
  1901. static::assertSame($zipEntry->getDosTime(), 0);
  1902. static::assertSame($zipEntry->getExtractedOS(), ZipPlatform::OS_DOS);
  1903. static::assertSame($zipEntry->getCreatedOS(), ZipPlatform::OS_DOS);
  1904. static::assertSame($zipEntry->getInternalAttributes(), 1);
  1905. static::assertSame($zipEntry->getExternalAttributes(), 0);
  1906. }
  1907. $zipFile->close();
  1908. }
  1909. /**
  1910. * @throws ZipException
  1911. */
  1912. public function testRenameWithRecompressData(): void
  1913. {
  1914. $entryName = 'file.txt';
  1915. $newEntryName = 'rename_file.txt';
  1916. $contents = str_repeat('Test' . \PHP_EOL, 1024);
  1917. $zipFile = new ZipFile();
  1918. $zipFile->addFromString($entryName, $contents, ZipCompressionMethod::DEFLATED);
  1919. $zipFile->saveAsFile($this->outputFilename);
  1920. $zipFile->close();
  1921. self::assertCorrectZipArchive($this->outputFilename);
  1922. $zipFile->openFile($this->outputFilename);
  1923. $zipFile->rename($entryName, $newEntryName);
  1924. $zipFile->setCompressionMethodEntry($newEntryName, ZipCompressionMethod::STORED);
  1925. $zipFile->saveAsFile($this->outputFilename);
  1926. $zipFile->close();
  1927. self::assertCorrectZipArchive($this->outputFilename);
  1928. $zipFile->openFile($this->outputFilename);
  1929. static::assertSame($zipFile->getEntry($newEntryName)->getCompressionMethod(), ZipCompressionMethod::STORED);
  1930. $zipFile->close();
  1931. }
  1932. /**
  1933. * @throws ZipEntryNotFoundException
  1934. * @throws ZipException
  1935. */
  1936. public function testCloneZipContainerInZipWriter(): void
  1937. {
  1938. $zipFile = new ZipFile();
  1939. $zipFile['file 1'] = 'contents';
  1940. $zipEntryBeforeWrite = $zipFile->getEntry('file 1');
  1941. $zipFile->saveAsFile($this->outputFilename);
  1942. $zipAfterBeforeWrite = $zipFile->getEntry('file 1');
  1943. static::assertSame($zipAfterBeforeWrite, $zipEntryBeforeWrite);
  1944. $zipFile->close();
  1945. }
  1946. /**
  1947. * @throws ZipException
  1948. */
  1949. public function testMultiSave(): void
  1950. {
  1951. $zipFile = new ZipFile();
  1952. $zipFile['file 1'] = 'contents';
  1953. for ($i = 0; $i < 10; $i++) {
  1954. $zipFile->saveAsFile($this->outputFilename);
  1955. self::assertCorrectZipArchive($this->outputFilename);
  1956. }
  1957. $zipFile->close();
  1958. }
  1959. /**
  1960. * @throws ZipEntryNotFoundException
  1961. * @throws ZipException
  1962. */
  1963. public function testNoData(): void
  1964. {
  1965. $this->expectException(ZipException::class);
  1966. $this->expectExceptionMessage('No data for zip entry file');
  1967. $entryName = 'file';
  1968. $zipFile = new ZipFile();
  1969. try {
  1970. $zipFile[$entryName] = '';
  1971. $zipEntry = $zipFile->getEntry($entryName);
  1972. $zipEntry->setData(null);
  1973. $zipFile->getEntryContents($entryName);
  1974. } finally {
  1975. $zipFile->close();
  1976. }
  1977. }
  1978. /**
  1979. * @throws ZipEntryNotFoundException
  1980. * @throws ZipException
  1981. */
  1982. public function testReplaceEntryContentsByFile(): void
  1983. {
  1984. $entryName = basename(__FILE__);
  1985. $zipFile = new ZipFile();
  1986. $zipFile[$entryName] = 'contents';
  1987. $zipFile->saveAsFile($this->outputFilename);
  1988. $zipFile->close();
  1989. $zipFile->openFile($this->outputFilename);
  1990. $entry = $zipFile->getEntry($entryName);
  1991. $data = new ZipFileData($entry, new \SplFileInfo(__FILE__));
  1992. $entry->setData($data);
  1993. $zipFile->saveAsFile($this->outputFilename);
  1994. $zipFile->close();
  1995. self::assertCorrectZipArchive($this->outputFilename);
  1996. $zipFile->openFile($this->outputFilename);
  1997. static::assertSame(
  1998. $zipFile->getEntryContents($entryName),
  1999. file_get_contents(__FILE__)
  2000. );
  2001. $zipFile->close();
  2002. }
  2003. }