2
0

ZipFileTest.php 76 KB

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