ZipFileTest.php 73 KB

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