ZipFileTest.php 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507
  1. <?php
  2. namespace PhpZip\Tests;
  3. use GuzzleHttp\Psr7\Response;
  4. use PhpZip\Constants\ZipCompressionLevel;
  5. use PhpZip\Constants\ZipCompressionMethod;
  6. use PhpZip\Constants\ZipPlatform;
  7. use PhpZip\Exception\InvalidArgumentException;
  8. use PhpZip\Exception\ZipEntryNotFoundException;
  9. use PhpZip\Exception\ZipException;
  10. use PhpZip\Exception\ZipUnsupportMethodException;
  11. use PhpZip\Model\Data\ZipFileData;
  12. use PhpZip\Model\ZipEntry;
  13. use PhpZip\Model\ZipInfo;
  14. use PhpZip\Util\FilesUtil;
  15. use PhpZip\ZipFile;
  16. use Psr\Http\Message\ResponseInterface;
  17. /**
  18. * ZipFile test.
  19. *
  20. * @internal
  21. *
  22. * @small
  23. */
  24. class ZipFileTest extends ZipTestCase
  25. {
  26. /**
  27. * @throws ZipException
  28. */
  29. public function testOpenFileCantExists()
  30. {
  31. $this->setExpectedException(ZipException::class, 'does not exist');
  32. $zipFile = new ZipFile();
  33. $zipFile->openFile(uniqid('', true));
  34. }
  35. /**
  36. * @throws ZipException
  37. */
  38. public function testOpenFileCantOpen()
  39. {
  40. $this->setExpectedException(ZipException::class, 'can\'t open');
  41. if (static::skipTestForRootUser()) {
  42. return;
  43. }
  44. static::assertNotFalse(file_put_contents($this->outputFilename, 'content'));
  45. static::assertTrue(chmod($this->outputFilename, 0222));
  46. $zipFile = new ZipFile();
  47. $zipFile->openFile($this->outputFilename);
  48. }
  49. /**
  50. * @throws ZipException
  51. */
  52. public function testOpenFileEmptyFile()
  53. {
  54. $this->setExpectedException(ZipException::class, 'Corrupt zip file');
  55. static::assertNotFalse(touch($this->outputFilename));
  56. $zipFile = new ZipFile();
  57. $zipFile->openFile($this->outputFilename);
  58. }
  59. /**
  60. * @throws ZipException
  61. * @throws \Exception
  62. */
  63. public function testOpenFileInvalidZip()
  64. {
  65. $this->setExpectedException(
  66. ZipException::class,
  67. 'Invalid zip file. The end of the central directory could not be found.'
  68. );
  69. static::assertNotFalse(file_put_contents($this->outputFilename, random_bytes(255)));
  70. $zipFile = new ZipFile();
  71. $zipFile->openFile($this->outputFilename);
  72. }
  73. /**
  74. * @throws ZipException
  75. */
  76. public function testOpenFromStringNullString()
  77. {
  78. $this->setExpectedException(InvalidArgumentException::class, 'Empty string passed');
  79. $zipFile = new ZipFile();
  80. $zipFile->openFromString(null);
  81. }
  82. /**
  83. * @throws ZipException
  84. */
  85. public function testOpenFromStringEmptyString()
  86. {
  87. $this->setExpectedException(InvalidArgumentException::class, 'Empty string passed');
  88. $zipFile = new ZipFile();
  89. $zipFile->openFromString('');
  90. }
  91. /**
  92. * @throws ZipException
  93. * @throws \Exception
  94. */
  95. public function testOpenFromStringInvalidZip()
  96. {
  97. $this->setExpectedException(
  98. ZipException::class,
  99. 'Invalid zip file. The end of the central directory could not be found.'
  100. );
  101. $zipFile = new ZipFile();
  102. $zipFile->openFromString(random_bytes(255));
  103. }
  104. /**
  105. * @throws ZipException
  106. */
  107. public function testOpenFromString()
  108. {
  109. $zipFile = new ZipFile();
  110. $zipFile->addFromString('file', 'content');
  111. $zipFile['file2'] = 'content 2';
  112. $zipContents = $zipFile->outputAsString();
  113. $zipFile->close();
  114. $zipFile->openFromString($zipContents);
  115. static::assertSame($zipFile->count(), 2);
  116. static::assertTrue(isset($zipFile['file']));
  117. static::assertTrue(isset($zipFile['file2']));
  118. static::assertSame($zipFile['file'], 'content');
  119. static::assertSame($zipFile['file2'], 'content 2');
  120. $zipFile->close();
  121. }
  122. /**
  123. * @throws ZipException
  124. */
  125. public function testOpenFromStreamNullStream()
  126. {
  127. $this->setExpectedException(InvalidArgumentException::class, 'Stream must be a resource');
  128. $zipFile = new ZipFile();
  129. $zipFile->openFromStream(null);
  130. }
  131. /**
  132. * @throws ZipException
  133. */
  134. public function testOpenFromStreamInvalidResourceType()
  135. {
  136. $this->setExpectedException(InvalidArgumentException::class, 'Stream must be a resource');
  137. $zipFile = new ZipFile();
  138. /** @noinspection PhpParamsInspection */
  139. $zipFile->openFromStream('stream resource');
  140. }
  141. /**
  142. * @throws ZipException
  143. */
  144. public function testOpenFromStreamInvalidResourceType2()
  145. {
  146. $this->setExpectedException(InvalidArgumentException::class, 'Invalid resource type');
  147. $zipFile = new ZipFile();
  148. if (!\extension_loaded('gd')) {
  149. static::markTestSkipped('not extension gd');
  150. return;
  151. }
  152. /** @noinspection PhpComposerExtensionStubsInspection */
  153. $zipFile->openFromStream(imagecreate(1, 1));
  154. }
  155. /**
  156. * @throws ZipException
  157. */
  158. public function testOpenFromStreamInvalidResourceType3()
  159. {
  160. $this->setExpectedException(InvalidArgumentException::class, 'Directory stream not supported');
  161. $zipFile = new ZipFile();
  162. $zipFile->openFromStream(opendir(__DIR__));
  163. }
  164. /**
  165. * @throws ZipException
  166. * @noinspection PhpUsageOfSilenceOperatorInspection
  167. * @noinspection NestedPositiveIfStatementsInspection
  168. */
  169. public function testOpenFromStreamNoSeekable()
  170. {
  171. $this->setExpectedException(InvalidArgumentException::class, 'The stream wrapper type "http" is not supported');
  172. if (!$fp = @fopen('http://localhost', 'rb')) {
  173. if (!$fp = @fopen('http://example.org', 'rb')) {
  174. static::markTestSkipped('not connected to localhost or remote host');
  175. return;
  176. }
  177. }
  178. $zipFile = new ZipFile();
  179. $zipFile->openFromStream($fp);
  180. }
  181. /**
  182. * @throws ZipException
  183. */
  184. public function testOpenFromStreamEmptyContents()
  185. {
  186. $this->setExpectedException(ZipException::class, 'Corrupt zip file');
  187. $fp = fopen($this->outputFilename, 'w+b');
  188. $zipFile = new ZipFile();
  189. $zipFile->openFromStream($fp);
  190. }
  191. /**
  192. * @throws ZipException
  193. * @throws \Exception
  194. */
  195. public function testOpenFromStreamInvalidZip()
  196. {
  197. $this->setExpectedException(
  198. ZipException::class,
  199. 'Invalid zip file. The end of the central directory could not be found.'
  200. );
  201. $fp = fopen($this->outputFilename, 'w+b');
  202. fwrite($fp, random_bytes(255));
  203. $zipFile = new ZipFile();
  204. $zipFile->openFromStream($fp);
  205. }
  206. /**
  207. * @throws ZipException
  208. */
  209. public function testOpenFromStream()
  210. {
  211. $zipFile = new ZipFile();
  212. $zipFile
  213. ->addFromString('file', 'content')
  214. ->saveAsFile($this->outputFilename)
  215. ->close()
  216. ;
  217. $handle = fopen($this->outputFilename, 'rb');
  218. $zipFile->openFromStream($handle);
  219. static::assertSame($zipFile->count(), 1);
  220. static::assertTrue(isset($zipFile['file']));
  221. static::assertSame($zipFile['file'], 'content');
  222. $zipFile->close();
  223. }
  224. /**
  225. * Test create, open and extract empty archive.
  226. *
  227. * @throws ZipException
  228. */
  229. public function testEmptyArchive()
  230. {
  231. $zipFile = new ZipFile();
  232. $zipFile
  233. ->saveAsFile($this->outputFilename)
  234. ->close()
  235. ;
  236. static::assertCorrectEmptyZip($this->outputFilename);
  237. static::assertTrue(mkdir($this->outputDirname, 0755, true));
  238. $zipFile->openFile($this->outputFilename);
  239. static::assertSame($zipFile->count(), 0);
  240. $zipFile
  241. ->extractTo($this->outputDirname)
  242. ->close()
  243. ;
  244. static::assertTrue(FilesUtil::isEmptyDir($this->outputDirname));
  245. }
  246. /**
  247. * No modified archive.
  248. *
  249. * @throws ZipException
  250. *
  251. * @see ZipOutputFile::create()
  252. */
  253. public function testNoModifiedArchive()
  254. {
  255. static::assertTrue(mkdir($this->outputDirname, 0755, true));
  256. $fileActual = $this->outputDirname . \DIRECTORY_SEPARATOR . 'file_actual.zip';
  257. $fileExpected = $this->outputDirname . \DIRECTORY_SEPARATOR . 'file_expected.zip';
  258. $zipFile = new ZipFile();
  259. $zipFile->addDirRecursive(__DIR__ . '/../src');
  260. $sourceCount = $zipFile->count();
  261. static::assertTrue($sourceCount > 0);
  262. $zipFile
  263. ->saveAsFile($fileActual)
  264. ->close()
  265. ;
  266. static::assertCorrectZipArchive($fileActual);
  267. $zipFile
  268. ->openFile($fileActual)
  269. ->saveAsFile($fileExpected)
  270. ;
  271. static::assertCorrectZipArchive($fileExpected);
  272. $zipFileExpected = new ZipFile();
  273. $zipFileExpected->openFile($fileExpected);
  274. static::assertSame($zipFile->count(), $sourceCount);
  275. static::assertSame($zipFileExpected->count(), $zipFile->count());
  276. static::assertSame($zipFileExpected->getListFiles(), $zipFile->getListFiles());
  277. foreach ($zipFile as $entryName => $content) {
  278. static::assertSame($zipFileExpected[$entryName], $content);
  279. }
  280. $zipFileExpected->close();
  281. $zipFile->close();
  282. }
  283. /**
  284. * Create archive and add files.
  285. *
  286. * @throws ZipException
  287. *
  288. * @see ZipOutputFile::addFromFile()
  289. * @see ZipOutputFile::addFromStream()
  290. * @see ZipFile::getEntryContents()
  291. * @see ZipOutputFile::addFromString()
  292. */
  293. public function testCreateArchiveAndAddFiles()
  294. {
  295. $outputFromString = file_get_contents(__FILE__);
  296. $outputFromString2 = file_get_contents(\dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'README.md');
  297. $outputFromFile = file_get_contents(\dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'phpunit.xml');
  298. $outputFromStream = file_get_contents(\dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'composer.json');
  299. $filenameFromString = basename(__FILE__);
  300. $filenameFromString2 = 'test_file.txt';
  301. $filenameFromFile = 'data/test file.txt';
  302. $filenameFromStream = 'data/ডিরেক্টরি/αρχείο.json';
  303. $emptyDirName = 'empty dir/пустой каталог/空目錄/ไดเรกทอรีที่ว่างเปล่า/';
  304. $emptyDirName2 = 'empty dir/пустой каталог/';
  305. $emptyDirName3 = 'empty dir/пустой каталог/ещё один пустой каталог/';
  306. $tempFile = tempnam(sys_get_temp_dir(), 'txt');
  307. file_put_contents($tempFile, $outputFromFile);
  308. $tempStream = tmpfile();
  309. fwrite($tempStream, $outputFromStream);
  310. $zipFile = new ZipFile();
  311. $zipFile
  312. ->addFromString($filenameFromString, $outputFromString)
  313. ->addFile($tempFile, $filenameFromFile)
  314. ->addFromStream($tempStream, $filenameFromStream)
  315. ->addEmptyDir($emptyDirName)
  316. ;
  317. $zipFile[$filenameFromString2] = $outputFromString2;
  318. $zipFile[$emptyDirName2] = null;
  319. $zipFile[$emptyDirName3] = 'this content ignoring';
  320. static::assertSame(\count($zipFile), 7);
  321. $zipFile
  322. ->saveAsFile($this->outputFilename)
  323. ->close()
  324. ;
  325. unlink($tempFile);
  326. static::assertCorrectZipArchive($this->outputFilename);
  327. $zipFile->openFile($this->outputFilename);
  328. static::assertSame(\count($zipFile), 7);
  329. static::assertSame($zipFile[$filenameFromString], $outputFromString);
  330. static::assertSame($zipFile[$filenameFromFile], $outputFromFile);
  331. static::assertSame($zipFile[$filenameFromStream], $outputFromStream);
  332. static::assertSame($zipFile[$filenameFromString2], $outputFromString2);
  333. static::assertTrue(isset($zipFile[$emptyDirName]));
  334. static::assertTrue(isset($zipFile[$emptyDirName2]));
  335. static::assertTrue(isset($zipFile[$emptyDirName3]));
  336. static::assertTrue($zipFile->isDirectory($emptyDirName));
  337. static::assertTrue($zipFile->isDirectory($emptyDirName2));
  338. static::assertTrue($zipFile->isDirectory($emptyDirName3));
  339. $listFiles = $zipFile->getListFiles();
  340. static::assertSame($listFiles[0], $filenameFromString);
  341. static::assertSame($listFiles[1], $filenameFromFile);
  342. static::assertSame($listFiles[2], $filenameFromStream);
  343. static::assertSame($listFiles[3], $emptyDirName);
  344. static::assertSame($listFiles[4], $filenameFromString2);
  345. static::assertSame($listFiles[5], $emptyDirName2);
  346. static::assertSame($listFiles[6], $emptyDirName3);
  347. $zipFile->close();
  348. }
  349. /**
  350. * @throws ZipException
  351. */
  352. public function testEmptyContent()
  353. {
  354. $zipFile = new ZipFile();
  355. $zipFile['file'] = '';
  356. $zipFile->saveAsFile($this->outputFilename);
  357. $zipFile->close();
  358. $zipFile->openFile($this->outputFilename);
  359. static::assertSame($zipFile['file'], '');
  360. $zipFile->close();
  361. }
  362. /**
  363. * Test compression method from image file.
  364. *
  365. * @throws ZipException
  366. */
  367. public function testCompressionMethodFromImageMimeType()
  368. {
  369. if (!\function_exists('mime_content_type')) {
  370. static::markTestSkipped('Function mime_content_type not exists');
  371. return;
  372. }
  373. $outputFilename = $this->outputFilename;
  374. $this->outputFilename .= '.gif';
  375. static::assertNotFalse(
  376. file_put_contents(
  377. $this->outputFilename,
  378. base64_decode('R0lGODlhAQABAJAAAP8AAAAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==')
  379. )
  380. );
  381. $basename = basename($this->outputFilename);
  382. $zipFile = new ZipFile();
  383. $zipFile->addFile($this->outputFilename, $basename);
  384. $zipFile->saveAsFile($outputFilename);
  385. unlink($this->outputFilename);
  386. $this->outputFilename = $outputFilename;
  387. $zipFile->openFile($this->outputFilename);
  388. $info = $zipFile->getEntryInfo($basename);
  389. static::assertSame($info->getMethodName(), 'Stored');
  390. $zipFile->close();
  391. }
  392. /**
  393. * Rename zip entry name.
  394. *
  395. * @throws ZipException
  396. */
  397. public function testRename()
  398. {
  399. $oldName = basename(__FILE__);
  400. $newName = 'tests/' . $oldName;
  401. $zipFile = new ZipFile();
  402. $zipFile->addDir(__DIR__);
  403. $zipFile->saveAsFile($this->outputFilename);
  404. $zipFile->close();
  405. static::assertCorrectZipArchive($this->outputFilename);
  406. $zipFile->openFile($this->outputFilename);
  407. $zipFile->rename($oldName, $newName);
  408. $zipFile->addFromString('file1.txt', 'content');
  409. $zipFile->addFromString('file2.txt', 'content');
  410. $zipFile->addFromString('file3.txt', 'content');
  411. $zipFile->rename('file1.txt', 'file_long_name.txt');
  412. $zipFile->rename('file2.txt', 'file4.txt');
  413. $zipFile->rename('file3.txt', 'fi.txt');
  414. $zipFile->saveAsFile($this->outputFilename);
  415. $zipFile->close();
  416. static::assertCorrectZipArchive($this->outputFilename);
  417. $zipFile->openFile($this->outputFilename);
  418. static::assertFalse(isset($zipFile[$oldName]));
  419. static::assertTrue(isset($zipFile[$newName]));
  420. static::assertFalse(isset($zipFile['file1.txt']));
  421. static::assertFalse(isset($zipFile['file2.txt']));
  422. static::assertFalse(isset($zipFile['file3.txt']));
  423. static::assertTrue(isset($zipFile['file_long_name.txt']));
  424. static::assertTrue(isset($zipFile['file4.txt']));
  425. static::assertTrue(isset($zipFile['fi.txt']));
  426. $zipFile->close();
  427. }
  428. /**
  429. * @throws ZipException
  430. */
  431. public function testRenameEntryNull()
  432. {
  433. $this->setExpectedException(InvalidArgumentException::class, 'name is null');
  434. $zipFile = new ZipFile();
  435. $zipFile->rename(null, 'new-file');
  436. }
  437. /**
  438. * @throws ZipException
  439. */
  440. public function testRenameEntryNull2()
  441. {
  442. $this->setExpectedException(InvalidArgumentException::class, 'name is null');
  443. $zipFile = new ZipFile();
  444. $zipFile->rename('old-file', null);
  445. }
  446. /**
  447. * @throws ZipException
  448. */
  449. public function testRenameEntryToExistsNewEntry()
  450. {
  451. $this->setExpectedException(InvalidArgumentException::class, 'is exists');
  452. $zipFile = new ZipFile();
  453. $zipFile['file'] = 'content';
  454. $zipFile['file2'] = 'content 2';
  455. $zipFile->saveAsFile($this->outputFilename);
  456. $zipFile->close();
  457. $zipFile = new ZipFile();
  458. $zipFile->openFile($this->outputFilename);
  459. $zipFile->rename('file2', 'file');
  460. }
  461. /**
  462. * @throws ZipException
  463. */
  464. public function testRenameEntryNotFound()
  465. {
  466. $this->setExpectedException(ZipEntryNotFoundException::class);
  467. $zipFile = new ZipFile();
  468. $zipFile['file'] = 'content';
  469. $zipFile['file2'] = 'content 2';
  470. $zipFile->saveAsFile($this->outputFilename);
  471. $zipFile->close();
  472. $zipFile = new ZipFile();
  473. $zipFile->openFile($this->outputFilename);
  474. $zipFile->rename('file2.bak', 'file3');
  475. }
  476. /**
  477. * Delete entry from name.
  478. *
  479. * @throws ZipException
  480. */
  481. public function testDeleteFromName()
  482. {
  483. $inputDir = \dirname(__DIR__) . \DIRECTORY_SEPARATOR;
  484. $deleteEntryName = 'composer.json';
  485. $zipFile = new ZipFile();
  486. $zipFile->addDir($inputDir);
  487. $zipFile->saveAsFile($this->outputFilename);
  488. $zipFile->close();
  489. static::assertCorrectZipArchive($this->outputFilename);
  490. $zipFile->openFile($this->outputFilename);
  491. $zipFile->deleteFromName($deleteEntryName);
  492. $zipFile->saveAsFile($this->outputFilename);
  493. $zipFile->close();
  494. static::assertCorrectZipArchive($this->outputFilename);
  495. $zipFile->openFile($this->outputFilename);
  496. static::assertFalse(isset($zipFile[$deleteEntryName]));
  497. $zipFile->close();
  498. }
  499. /**
  500. * @throws ZipEntryNotFoundException
  501. * @throws ZipException
  502. */
  503. public function testDeleteNewEntry()
  504. {
  505. $zipFile = new ZipFile();
  506. $zipFile['entry1'] = '';
  507. $zipFile['entry2'] = '';
  508. $zipFile->deleteFromName('entry2');
  509. $zipFile->saveAsFile($this->outputFilename);
  510. $zipFile->close();
  511. $zipFile->openFile($this->outputFilename);
  512. static::assertSame(\count($zipFile), 1);
  513. static::assertTrue(isset($zipFile['entry1']));
  514. static::assertFalse(isset($zipFile['entry2']));
  515. $zipFile->close();
  516. }
  517. /**
  518. * @throws ZipEntryNotFoundException
  519. */
  520. public function testDeleteFromNameNotFoundEntry()
  521. {
  522. $this->setExpectedException(ZipEntryNotFoundException::class);
  523. $zipFile = new ZipFile();
  524. $zipFile->deleteFromName('entry');
  525. }
  526. public function testCatchNotFoundEntry()
  527. {
  528. $entryName = 'entry';
  529. $zipFile = new ZipFile();
  530. try {
  531. $zipFile->getEntry($entryName);
  532. } catch (ZipEntryNotFoundException $e) {
  533. static::assertSame($e->getEntryName(), $entryName);
  534. }
  535. }
  536. /**
  537. * Delete zip entries from glob pattern.
  538. *
  539. * @throws ZipException
  540. */
  541. public function testDeleteFromGlob()
  542. {
  543. $inputDir = \dirname(__DIR__);
  544. $zipFile = new ZipFile();
  545. $zipFile->addFilesFromGlobRecursive($inputDir, '**.{xml,json,md}', '/');
  546. static::assertTrue(isset($zipFile['composer.json']));
  547. static::assertTrue(isset($zipFile['phpunit.xml']));
  548. $zipFile->saveAsFile($this->outputFilename);
  549. $zipFile->close();
  550. static::assertCorrectZipArchive($this->outputFilename);
  551. $zipFile->openFile($this->outputFilename);
  552. static::assertTrue(isset($zipFile['composer.json']));
  553. static::assertTrue(isset($zipFile['phpunit.xml']));
  554. $zipFile->deleteFromGlob('**.{xml,json}');
  555. static::assertFalse(isset($zipFile['composer.json']));
  556. static::assertFalse(isset($zipFile['phpunit.xml']));
  557. $zipFile->saveAsFile($this->outputFilename);
  558. $zipFile->close();
  559. static::assertCorrectZipArchive($this->outputFilename);
  560. $zipFile->openFile($this->outputFilename);
  561. static::assertTrue($zipFile->count() > 0);
  562. foreach ($zipFile->getListFiles() as $name) {
  563. static::assertStringEndsWith('.md', $name);
  564. }
  565. $zipFile->close();
  566. }
  567. public function testDeleteFromGlobFailNull()
  568. {
  569. $this->setExpectedException(InvalidArgumentException::class, 'The glob pattern is not specified');
  570. $zipFile = new ZipFile();
  571. $zipFile->deleteFromGlob(null);
  572. }
  573. public function testDeleteFromGlobFailEmpty()
  574. {
  575. $this->setExpectedException(InvalidArgumentException::class, 'The glob pattern is not specified');
  576. $zipFile = new ZipFile();
  577. $zipFile->deleteFromGlob('');
  578. }
  579. /**
  580. * Delete entries from regex pattern.
  581. *
  582. * @throws ZipException
  583. */
  584. public function testDeleteFromRegex()
  585. {
  586. $inputDir = \dirname(__DIR__);
  587. $zipFile = new ZipFile();
  588. $zipFile->addFilesFromRegexRecursive($inputDir, '~\.(xml|json)$~i', 'Path');
  589. $zipFile->saveAsFile($this->outputFilename);
  590. $zipFile->close();
  591. static::assertCorrectZipArchive($this->outputFilename);
  592. $zipFile->openFile($this->outputFilename);
  593. $zipFile->deleteFromRegex('~\.(json)$~i');
  594. $zipFile->addFromString('test.txt', 'content');
  595. $zipFile->deleteFromRegex('~\.txt$~');
  596. $zipFile->saveAsFile($this->outputFilename);
  597. $zipFile->close();
  598. static::assertCorrectZipArchive($this->outputFilename);
  599. $zipFile->openFile($this->outputFilename);
  600. static::assertFalse(isset($zipFile['Path/composer.json']));
  601. static::assertFalse(isset($zipFile['Path/test.txt']));
  602. static::assertTrue(isset($zipFile['Path/phpunit.xml']));
  603. $zipFile->close();
  604. }
  605. public function testDeleteFromRegexFailNull()
  606. {
  607. $this->setExpectedException(InvalidArgumentException::class, 'The regex pattern is not specified');
  608. $zipFile = new ZipFile();
  609. $zipFile->deleteFromRegex(null);
  610. }
  611. public function testDeleteFromRegexFailEmpty()
  612. {
  613. $this->setExpectedException(InvalidArgumentException::class, 'The regex pattern is not specified');
  614. $zipFile = new ZipFile();
  615. $zipFile->deleteFromRegex('');
  616. }
  617. /**
  618. * Delete all entries.
  619. *
  620. * @throws ZipException
  621. */
  622. public function testDeleteAll()
  623. {
  624. $zipFile = new ZipFile();
  625. $zipFile->addDirRecursive(\dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'src');
  626. static::assertTrue($zipFile->count() > 0);
  627. $zipFile->saveAsFile($this->outputFilename);
  628. $zipFile->close();
  629. static::assertCorrectZipArchive($this->outputFilename);
  630. $zipFile->openFile($this->outputFilename);
  631. static::assertTrue($zipFile->count() > 0);
  632. $zipFile->deleteAll();
  633. $zipFile->saveAsFile($this->outputFilename);
  634. $zipFile->close();
  635. static::assertCorrectEmptyZip($this->outputFilename);
  636. $zipFile->openFile($this->outputFilename);
  637. static::assertSame($zipFile->count(), 0);
  638. $zipFile->close();
  639. }
  640. /**
  641. * Test zip archive comment.
  642. *
  643. * @throws ZipException
  644. */
  645. public function testArchiveComment()
  646. {
  647. $comment = 'This zip file comment' . \PHP_EOL
  648. . 'Αυτό το σχόλιο αρχείο zip' . \PHP_EOL
  649. . 'Это комментарий zip архива' . \PHP_EOL
  650. . '這個ZIP文件註釋' . \PHP_EOL
  651. . 'ეს zip ფაილის კომენტარი' . \PHP_EOL
  652. . 'このzipファイルにコメント' . \PHP_EOL
  653. . 'ความคิดเห็นนี้ไฟล์ซิป';
  654. $zipFile = new ZipFile();
  655. $zipFile->setArchiveComment($comment);
  656. $zipFile->addFile(__FILE__);
  657. $zipFile->saveAsFile($this->outputFilename);
  658. $zipFile->close();
  659. static::assertCorrectZipArchive($this->outputFilename);
  660. $zipFile->openFile($this->outputFilename);
  661. static::assertSame($zipFile->getArchiveComment(), $comment);
  662. $zipFile->setArchiveComment(null); // remove archive comment
  663. $zipFile->saveAsFile($this->outputFilename);
  664. $zipFile->close();
  665. static::assertCorrectZipArchive($this->outputFilename);
  666. // check empty comment
  667. $zipFile->openFile($this->outputFilename);
  668. static::assertNull($zipFile->getArchiveComment());
  669. $zipFile->close();
  670. }
  671. /**
  672. * Test very long archive comment.
  673. */
  674. public function testVeryLongArchiveComment()
  675. {
  676. $this->setExpectedException(InvalidArgumentException::class);
  677. $comment = 'Very long comment' . \PHP_EOL .
  678. 'Очень длинный комментарий' . \PHP_EOL;
  679. $comment = str_repeat($comment, ceil(0xffff / \strlen($comment)) + \strlen($comment) + 1);
  680. $zipFile = new ZipFile();
  681. $zipFile->setArchiveComment($comment);
  682. }
  683. /**
  684. * Test zip entry comment.
  685. *
  686. * @throws ZipException
  687. * @throws \Exception
  688. */
  689. public function testEntryComment()
  690. {
  691. $entries = [
  692. '文件1.txt' => [
  693. 'data' => random_bytes(255),
  694. 'comment' => '這是註釋的條目。',
  695. ],
  696. 'file2.txt' => [
  697. 'data' => random_bytes(255),
  698. 'comment' => null,
  699. ],
  700. 'file3.txt' => [
  701. 'data' => random_bytes(255),
  702. 'comment' => random_bytes(255),
  703. ],
  704. 'file4.txt' => [
  705. 'data' => random_bytes(255),
  706. 'comment' => 'Комментарий файла',
  707. ],
  708. 'file5.txt' => [
  709. 'data' => random_bytes(255),
  710. 'comment' => 'ไฟล์แสดงความคิดเห็น',
  711. ],
  712. 'file6 emoji 🙍🏼.txt' => [
  713. 'data' => random_bytes(255),
  714. 'comment' => 'Emoji comment file - 😀 ⛈ ❤️ 🤴🏽',
  715. ],
  716. ];
  717. // create archive with entry comments
  718. $zipFile = new ZipFile();
  719. foreach ($entries as $entryName => $item) {
  720. $zipFile->addFromString($entryName, $item['data']);
  721. $zipFile->setEntryComment($entryName, $item['comment']);
  722. }
  723. $zipFile->saveAsFile($this->outputFilename);
  724. $zipFile->close();
  725. static::assertCorrectZipArchive($this->outputFilename);
  726. // check and modify comments
  727. $zipFile->openFile($this->outputFilename);
  728. foreach ($zipFile->getListFiles() as $entryName) {
  729. $entriesItem = $entries[$entryName];
  730. static::assertNotEmpty($entriesItem);
  731. static::assertSame($zipFile[$entryName], $entriesItem['data']);
  732. static::assertSame($zipFile->getEntryComment($entryName), (string) $entriesItem['comment']);
  733. }
  734. // modify comment
  735. $entries['file5.txt']['comment'] = mt_rand(1, 100000000);
  736. $zipFile->setEntryComment('file5.txt', $entries['file5.txt']['comment']);
  737. $zipFile->saveAsFile($this->outputFilename);
  738. $zipFile->close();
  739. static::assertCorrectZipArchive($this->outputFilename);
  740. // check modify comments
  741. $zipFile->openFile($this->outputFilename);
  742. foreach ($entries as $entryName => $entriesItem) {
  743. static::assertTrue(isset($zipFile[$entryName]));
  744. static::assertSame($zipFile->getEntryComment($entryName), (string) $entriesItem['comment']);
  745. static::assertSame($zipFile[$entryName], $entriesItem['data']);
  746. }
  747. $zipFile->close();
  748. }
  749. /**
  750. * Test zip entry very long comment.
  751. *
  752. * @throws ZipException
  753. */
  754. public function testVeryLongEntryComment()
  755. {
  756. $this->setExpectedException(InvalidArgumentException::class, 'Comment too long');
  757. $comment = 'Very long comment' . \PHP_EOL .
  758. 'Очень длинный комментарий' . \PHP_EOL;
  759. $comment = str_repeat($comment, ceil(0xffff / \strlen($comment)) + \strlen($comment) + 1);
  760. $zipFile = new ZipFile();
  761. $zipFile->addFile(__FILE__, 'test');
  762. $zipFile->setEntryComment('test', $comment);
  763. }
  764. /**
  765. * @throws ZipException
  766. */
  767. public function testSetEntryCommentNotFoundEntry()
  768. {
  769. $this->setExpectedException(ZipEntryNotFoundException::class);
  770. $zipFile = new ZipFile();
  771. $zipFile->setEntryComment('test', 'comment');
  772. }
  773. /**
  774. * Test all available support compression methods.
  775. *
  776. * @throws ZipException
  777. * @throws \Exception
  778. */
  779. public function testCompressionMethod()
  780. {
  781. $entries = [
  782. '1' => [
  783. 'data' => random_bytes(255),
  784. 'method' => ZipCompressionMethod::STORED,
  785. 'expected' => 'Stored',
  786. ],
  787. '2' => [
  788. 'data' => random_bytes(255),
  789. 'method' => ZipCompressionMethod::DEFLATED,
  790. 'expected' => 'Deflated',
  791. ],
  792. ];
  793. if (\extension_loaded('bz2')) {
  794. $entries['3'] = [
  795. 'data' => random_bytes(255),
  796. 'method' => ZipCompressionMethod::BZIP2,
  797. 'expected' => 'BZIP2',
  798. ];
  799. }
  800. $zipFile = new ZipFile();
  801. foreach ($entries as $entryName => $item) {
  802. $zipFile->addFromString($entryName, $item['data'], $item['method']);
  803. }
  804. $zipFile->saveAsFile($this->outputFilename);
  805. $zipFile->close();
  806. static::assertCorrectZipArchive($this->outputFilename);
  807. $zipFile->openFile($this->outputFilename);
  808. $zipFile->setCompressionLevel(ZipCompressionLevel::MAXIMUM);
  809. $zipAllInfo = $zipFile->getAllInfo();
  810. foreach ($zipAllInfo as $entryName => $info) {
  811. static::assertSame($zipFile[$entryName], $entries[$entryName]['data']);
  812. static::assertSame($info->getMethodName(), $entries[$entryName]['expected']);
  813. $entryInfo = $zipFile->getEntryInfo($entryName);
  814. static::assertEquals($entryInfo, $info);
  815. }
  816. $zipFile->close();
  817. }
  818. /**
  819. * @dataProvider provideInvalidCompressionLevels
  820. *
  821. * @param int $compressionLevel
  822. */
  823. public function testSetInvalidCompressionLevel($compressionLevel)
  824. {
  825. $this->setExpectedException(
  826. InvalidArgumentException::class,
  827. 'Invalid compression level. Minimum level 1. Maximum level 9'
  828. );
  829. $zipFile = new ZipFile();
  830. $zipFile['file 1'] = 'contents';
  831. $zipFile->setCompressionLevel($compressionLevel);
  832. }
  833. /**
  834. * @return array
  835. */
  836. public function provideInvalidCompressionLevels()
  837. {
  838. return [
  839. [-10],
  840. [-2],
  841. [10],
  842. [0xffff],
  843. ];
  844. }
  845. /**
  846. * Test extract all files.
  847. *
  848. * @throws ZipException
  849. * @throws \Exception
  850. */
  851. public function testExtract()
  852. {
  853. $entries = [
  854. 'test1.txt' => random_bytes(255),
  855. 'test2.txt' => random_bytes(255),
  856. 'test/test 2/test3.txt' => random_bytes(255),
  857. 'test empty/dir/' => null,
  858. ];
  859. $zipFile = new ZipFile();
  860. foreach ($entries as $entryName => $contents) {
  861. if ($contents === null) {
  862. $zipFile->addEmptyDir($entryName);
  863. } else {
  864. $zipFile->addFromString($entryName, $contents);
  865. }
  866. }
  867. $zipFile->saveAsFile($this->outputFilename);
  868. $zipFile->close();
  869. static::assertTrue(mkdir($this->outputDirname, 0755, true));
  870. $zipFile->openFile($this->outputFilename);
  871. $zipFile->extractTo($this->outputDirname, null, [], $extractedEntries);
  872. foreach ($entries as $entryName => $contents) {
  873. $fullExtractedFilename = $this->outputDirname . \DIRECTORY_SEPARATOR . $entryName;
  874. static::assertTrue(
  875. isset($extractedEntries[$fullExtractedFilename]),
  876. 'No extract info for ' . $fullExtractedFilename
  877. );
  878. if ($contents === null) {
  879. static::assertTrue(is_dir($fullExtractedFilename));
  880. static::assertTrue(FilesUtil::isEmptyDir($fullExtractedFilename));
  881. } else {
  882. static::assertTrue(is_file($fullExtractedFilename));
  883. $contents = file_get_contents($fullExtractedFilename);
  884. static::assertSame($contents, $contents);
  885. }
  886. /** @var ZipEntry $entry */
  887. $entry = $extractedEntries[$fullExtractedFilename];
  888. static::assertSame($entry->getName(), $entryName);
  889. }
  890. $zipFile->close();
  891. }
  892. /**
  893. * Test extract some files.
  894. *
  895. * @throws ZipException
  896. * @throws \Exception
  897. */
  898. public function testExtractSomeFiles()
  899. {
  900. $entries = [
  901. 'test1.txt' => random_bytes(255),
  902. 'test2.txt' => random_bytes(255),
  903. 'test3.txt' => random_bytes(255),
  904. 'test4.txt' => random_bytes(255),
  905. 'test5.txt' => random_bytes(255),
  906. 'test/test/test.txt' => random_bytes(255),
  907. 'test/test/test 2.txt' => random_bytes(255),
  908. 'test empty/dir/' => null,
  909. 'test empty/dir2/' => null,
  910. ];
  911. $extractEntries = [
  912. 'test1.txt',
  913. 'test3.txt',
  914. 'test5.txt',
  915. 'test/test/test 2.txt',
  916. 'test empty/dir2/',
  917. ];
  918. static::assertTrue(mkdir($this->outputDirname, 0755, true));
  919. $zipFile = new ZipFile();
  920. $zipFile->addAll($entries);
  921. $zipFile->saveAsFile($this->outputFilename);
  922. $zipFile->close();
  923. $zipFile->openFile($this->outputFilename);
  924. $zipFile->extractTo($this->outputDirname, $extractEntries);
  925. foreach ($entries as $entryName => $value) {
  926. $fullExtractFilename = $this->outputDirname . \DIRECTORY_SEPARATOR . $entryName;
  927. if (\in_array($entryName, $extractEntries, true)) {
  928. if ($value === null) {
  929. static::assertTrue(is_dir($fullExtractFilename));
  930. static::assertTrue(FilesUtil::isEmptyDir($fullExtractFilename));
  931. } else {
  932. static::assertTrue(is_file($fullExtractFilename));
  933. $contents = file_get_contents($fullExtractFilename);
  934. static::assertEquals($contents, $value);
  935. }
  936. } elseif ($value === null) {
  937. static::assertFalse(is_dir($fullExtractFilename));
  938. } else {
  939. static::assertFalse(is_file($fullExtractFilename));
  940. }
  941. }
  942. static::assertFalse(is_file($this->outputDirname . \DIRECTORY_SEPARATOR . 'test/test/test.txt'));
  943. $zipFile->extractTo($this->outputDirname, 'test/test/test.txt');
  944. static::assertTrue(is_file($this->outputDirname . \DIRECTORY_SEPARATOR . 'test/test/test.txt'));
  945. $zipFile->close();
  946. }
  947. /**
  948. * @throws ZipException
  949. */
  950. public function testExtractFail()
  951. {
  952. $this->setExpectedException(ZipException::class, 'not found');
  953. $zipFile = new ZipFile();
  954. $zipFile['file'] = 'content';
  955. $zipFile->saveAsFile($this->outputFilename);
  956. $zipFile->close();
  957. $zipFile->openFile($this->outputFilename);
  958. $zipFile->extractTo('path/to/path');
  959. }
  960. /**
  961. * @throws ZipException
  962. */
  963. public function testExtractFail2()
  964. {
  965. $this->setExpectedException(ZipException::class, 'Destination is not directory');
  966. $zipFile = new ZipFile();
  967. $zipFile['file'] = 'content';
  968. $zipFile->saveAsFile($this->outputFilename);
  969. $zipFile->close();
  970. $zipFile->openFile($this->outputFilename);
  971. $zipFile->extractTo($this->outputFilename);
  972. }
  973. /**
  974. * @throws ZipException
  975. */
  976. public function testExtractFail3()
  977. {
  978. $this->setExpectedException(ZipException::class, 'Destination is not writable directory');
  979. if (static::skipTestForRootUser()) {
  980. return;
  981. }
  982. $zipFile = new ZipFile();
  983. $zipFile['file'] = 'content';
  984. $zipFile->saveAsFile($this->outputFilename);
  985. $zipFile->close();
  986. static::assertTrue(mkdir($this->outputDirname, 0444, true));
  987. static::assertTrue(chmod($this->outputDirname, 0444));
  988. $zipFile->openFile($this->outputFilename);
  989. $zipFile->extractTo($this->outputDirname);
  990. }
  991. /**
  992. * @noinspection OnlyWritesOnParameterInspection
  993. */
  994. public function testAddFromArrayAccessNullName()
  995. {
  996. $this->setExpectedException(
  997. InvalidArgumentException::class,
  998. 'Key must not be null, but must contain the name of the zip entry.'
  999. );
  1000. $zipFile = new ZipFile();
  1001. $zipFile[null] = 'content';
  1002. }
  1003. /**
  1004. * @noinspection OnlyWritesOnParameterInspection
  1005. */
  1006. public function testAddFromArrayAccessEmptyName()
  1007. {
  1008. $this->setExpectedException(
  1009. InvalidArgumentException::class,
  1010. 'Key is empty, but must contain the name of the zip entry.'
  1011. );
  1012. $zipFile = new ZipFile();
  1013. $zipFile[''] = 'content';
  1014. }
  1015. /**
  1016. * @throws ZipException
  1017. */
  1018. public function testAddFromStringNullContents()
  1019. {
  1020. $this->setExpectedException(InvalidArgumentException::class, 'Contents is null');
  1021. $zipFile = new ZipFile();
  1022. $zipFile->addFromString('file', null);
  1023. }
  1024. /**
  1025. * @throws ZipException
  1026. */
  1027. public function testAddFromStringNullEntryName()
  1028. {
  1029. $this->setExpectedException(InvalidArgumentException::class, 'Entry name is null');
  1030. $zipFile = new ZipFile();
  1031. $zipFile->addFromString(null, 'contents');
  1032. }
  1033. /**
  1034. * @throws ZipException
  1035. */
  1036. public function testAddFromStringUnsupportedMethod()
  1037. {
  1038. $this->setExpectedException(
  1039. ZipUnsupportMethodException::class,
  1040. 'Compression method 99 (AES Encryption) is not supported.'
  1041. );
  1042. $zipFile = new ZipFile();
  1043. $zipFile->addFromString('file', 'contents', ZipCompressionMethod::WINZIP_AES);
  1044. $zipFile->outputAsString();
  1045. }
  1046. /**
  1047. * @throws ZipException
  1048. */
  1049. public function testAddFromStringEmptyEntryName()
  1050. {
  1051. $this->setExpectedException(InvalidArgumentException::class, 'Empty entry name');
  1052. $zipFile = new ZipFile();
  1053. $zipFile->addFromString('', 'contents');
  1054. }
  1055. /**
  1056. * Test compression method from add string.
  1057. *
  1058. * @throws ZipException
  1059. */
  1060. public function testAddFromStringCompressionMethod()
  1061. {
  1062. $fileStored = sys_get_temp_dir() . '/zip-stored.txt';
  1063. $fileDeflated = sys_get_temp_dir() . '/zip-deflated.txt';
  1064. static::assertNotFalse(file_put_contents($fileStored, 'content'));
  1065. static::assertNotFalse(file_put_contents($fileDeflated, str_repeat('content', 200)));
  1066. $zipFile = new ZipFile();
  1067. $zipFile->addFromString(basename($fileStored), file_get_contents($fileStored));
  1068. $zipFile->addFromString(basename($fileDeflated), file_get_contents($fileDeflated));
  1069. $zipFile->saveAsFile($this->outputFilename);
  1070. $zipFile->close();
  1071. unlink($fileStored);
  1072. unlink($fileDeflated);
  1073. $zipFile->openFile($this->outputFilename);
  1074. $infoStored = $zipFile->getEntryInfo(basename($fileStored));
  1075. $infoDeflated = $zipFile->getEntryInfo(basename($fileDeflated));
  1076. static::assertSame($infoStored->getMethodName(), 'Stored');
  1077. static::assertSame($infoDeflated->getMethodName(), 'Deflated');
  1078. $zipFile->close();
  1079. }
  1080. /**
  1081. * @throws ZipException
  1082. */
  1083. public function testAddFromStreamInvalidResource()
  1084. {
  1085. $this->setExpectedException(InvalidArgumentException::class, 'Stream is not resource');
  1086. $zipFile = new ZipFile();
  1087. /** @noinspection PhpParamsInspection */
  1088. $zipFile->addFromStream('invalid resource', 'name');
  1089. }
  1090. /**
  1091. * @throws ZipException
  1092. */
  1093. public function testAddFromStreamEmptyEntryName()
  1094. {
  1095. $this->setExpectedException(InvalidArgumentException::class, 'Empty entry name');
  1096. $handle = fopen(__FILE__, 'rb');
  1097. $zipFile = new ZipFile();
  1098. $zipFile->addFromStream($handle, '');
  1099. }
  1100. /**
  1101. * @throws ZipException
  1102. */
  1103. public function testAddFromStreamUnsupportedMethod()
  1104. {
  1105. $this->setExpectedException(
  1106. ZipUnsupportMethodException::class,
  1107. 'Compression method 99 (AES Encryption) is not supported.'
  1108. );
  1109. $handle = fopen(__FILE__, 'rb');
  1110. $zipFile = new ZipFile();
  1111. $zipFile->addFromStream($handle, basename(__FILE__), ZipCompressionMethod::WINZIP_AES);
  1112. $zipFile->outputAsString();
  1113. }
  1114. /**
  1115. * Test compression method from add stream.
  1116. *
  1117. * @throws ZipException
  1118. */
  1119. public function testAddFromStreamCompressionMethod()
  1120. {
  1121. $fileStored = sys_get_temp_dir() . '/zip-stored.txt';
  1122. $fileDeflated = sys_get_temp_dir() . '/zip-deflated.txt';
  1123. static::assertNotFalse(file_put_contents($fileStored, 'content'));
  1124. static::assertNotFalse(file_put_contents($fileDeflated, str_repeat('content', 200)));
  1125. $fpStored = fopen($fileStored, 'rb');
  1126. $fpDeflated = fopen($fileDeflated, 'rb');
  1127. $zipFile = new ZipFile();
  1128. $zipFile->addFromStream($fpStored, basename($fileStored));
  1129. $zipFile->addFromStream($fpDeflated, basename($fileDeflated));
  1130. $zipFile->saveAsFile($this->outputFilename);
  1131. $zipFile->close();
  1132. unlink($fileStored);
  1133. unlink($fileDeflated);
  1134. $zipFile->openFile($this->outputFilename);
  1135. $infoStored = $zipFile->getEntryInfo(basename($fileStored));
  1136. $infoDeflated = $zipFile->getEntryInfo(basename($fileDeflated));
  1137. static::assertSame($infoStored->getMethodName(), 'Stored');
  1138. static::assertSame($infoDeflated->getMethodName(), 'Deflated');
  1139. $zipFile->close();
  1140. }
  1141. /**
  1142. * @throws ZipException
  1143. */
  1144. public function testAddFileNullFileName()
  1145. {
  1146. $this->setExpectedException(InvalidArgumentException::class, 'Filename is null');
  1147. $zipFile = new ZipFile();
  1148. $zipFile->addFile(null);
  1149. }
  1150. /**
  1151. * @throws ZipException
  1152. */
  1153. public function testAddFileCantExists()
  1154. {
  1155. $this->setExpectedException(InvalidArgumentException::class, 'File path/to/file is not readable');
  1156. $zipFile = new ZipFile();
  1157. $zipFile->addFile('path/to/file');
  1158. }
  1159. /**
  1160. * @throws ZipException
  1161. */
  1162. public function testAddFileUnsupportedMethod()
  1163. {
  1164. $this->setExpectedException(
  1165. ZipUnsupportMethodException::class,
  1166. 'Compression method 99 (AES Encryption) is not supported.'
  1167. );
  1168. $zipFile = new ZipFile();
  1169. $zipFile->addFile(__FILE__, null, ZipCompressionMethod::WINZIP_AES);
  1170. $zipFile->outputAsString();
  1171. }
  1172. /**
  1173. * @throws ZipException
  1174. */
  1175. public function testAddFileCantOpen()
  1176. {
  1177. $this->setExpectedException(InvalidArgumentException::class, 'is not readable');
  1178. if (static::skipTestForRootUser()) {
  1179. return;
  1180. }
  1181. static::assertNotFalse(file_put_contents($this->outputFilename, ''));
  1182. static::assertTrue(chmod($this->outputFilename, 0244));
  1183. $zipFile = new ZipFile();
  1184. $zipFile->addFile($this->outputFilename);
  1185. }
  1186. /**
  1187. * @throws ZipException
  1188. */
  1189. public function testAddDirNullDirname()
  1190. {
  1191. $this->setExpectedException(InvalidArgumentException::class, 'Input dir is null');
  1192. $zipFile = new ZipFile();
  1193. $zipFile->addDir(null);
  1194. }
  1195. /**
  1196. * @throws ZipException
  1197. */
  1198. public function testAddDirEmptyDirname()
  1199. {
  1200. $this->setExpectedException(InvalidArgumentException::class, 'The input directory is not specified');
  1201. $zipFile = new ZipFile();
  1202. $zipFile->addDir('');
  1203. }
  1204. /**
  1205. * @throws ZipException
  1206. */
  1207. public function testAddDirCantExists()
  1208. {
  1209. $this->setExpectedException(InvalidArgumentException::class, 'does not exist');
  1210. $zipFile = new ZipFile();
  1211. $zipFile->addDir(uniqid('', true));
  1212. }
  1213. /**
  1214. * @throws ZipException
  1215. */
  1216. public function testAddDirRecursiveNullDirname()
  1217. {
  1218. $this->setExpectedException(InvalidArgumentException::class, 'Input dir is null');
  1219. $zipFile = new ZipFile();
  1220. $zipFile->addDirRecursive(null);
  1221. }
  1222. /**
  1223. * @throws ZipException
  1224. */
  1225. public function testAddDirRecursiveEmptyDirname()
  1226. {
  1227. $this->setExpectedException(InvalidArgumentException::class, 'The input directory is not specified');
  1228. $zipFile = new ZipFile();
  1229. $zipFile->addDirRecursive('');
  1230. }
  1231. /**
  1232. * @throws ZipException
  1233. */
  1234. public function testAddDirRecursiveCantExists()
  1235. {
  1236. $this->setExpectedException(InvalidArgumentException::class, 'does not exist');
  1237. $zipFile = new ZipFile();
  1238. $zipFile->addDirRecursive(uniqid('', true));
  1239. }
  1240. /**
  1241. * @throws ZipException
  1242. */
  1243. public function testAddFilesFromGlobNull()
  1244. {
  1245. $this->setExpectedException(InvalidArgumentException::class, 'Input dir is null');
  1246. $zipFile = new ZipFile();
  1247. $zipFile->addFilesFromGlob(null, '*.png');
  1248. }
  1249. /**
  1250. * @throws ZipException
  1251. */
  1252. public function testAddFilesFromGlobEmpty()
  1253. {
  1254. $this->setExpectedException(InvalidArgumentException::class, 'The input directory is not specified');
  1255. $zipFile = new ZipFile();
  1256. $zipFile->addFilesFromGlob('', '*.png');
  1257. }
  1258. /**
  1259. * @throws ZipException
  1260. */
  1261. public function testAddFilesFromGlobCantExists()
  1262. {
  1263. $this->setExpectedException(InvalidArgumentException::class, 'does not exist');
  1264. $zipFile = new ZipFile();
  1265. $zipFile->addFilesFromGlob('path/to/path', '*.png');
  1266. }
  1267. /**
  1268. * @throws ZipException
  1269. */
  1270. public function testAddFilesFromGlobNullPattern()
  1271. {
  1272. $this->setExpectedException(InvalidArgumentException::class, 'The glob pattern is not specified');
  1273. $zipFile = new ZipFile();
  1274. $zipFile->addFilesFromGlob(__DIR__, null);
  1275. }
  1276. /**
  1277. * @throws ZipException
  1278. */
  1279. public function testAddFilesFromGlobEmptyPattern()
  1280. {
  1281. $this->setExpectedException(InvalidArgumentException::class, 'The glob pattern is not specified');
  1282. $zipFile = new ZipFile();
  1283. $zipFile->addFilesFromGlob(__DIR__, '');
  1284. }
  1285. /**
  1286. * @throws ZipException
  1287. */
  1288. public function testAddFilesFromGlobRecursiveNull()
  1289. {
  1290. $this->setExpectedException(InvalidArgumentException::class, 'Input dir is null');
  1291. $zipFile = new ZipFile();
  1292. $zipFile->addFilesFromGlobRecursive(null, '*.png');
  1293. }
  1294. /**
  1295. * @throws ZipException
  1296. */
  1297. public function testAddFilesFromGlobRecursiveEmpty()
  1298. {
  1299. $this->setExpectedException(InvalidArgumentException::class, 'The input directory is not specified');
  1300. $zipFile = new ZipFile();
  1301. $zipFile->addFilesFromGlobRecursive('', '*.png');
  1302. }
  1303. /**
  1304. * @throws ZipException
  1305. */
  1306. public function testAddFilesFromGlobRecursiveCantExists()
  1307. {
  1308. $this->setExpectedException(InvalidArgumentException::class, 'does not exist');
  1309. $zipFile = new ZipFile();
  1310. $zipFile->addFilesFromGlobRecursive('path/to/path', '*.png');
  1311. }
  1312. /**
  1313. * @throws ZipException
  1314. */
  1315. public function testAddFilesFromGlobRecursiveNullPattern()
  1316. {
  1317. $this->setExpectedException(InvalidArgumentException::class, 'The glob pattern is not specified');
  1318. $zipFile = new ZipFile();
  1319. $zipFile->addFilesFromGlobRecursive(__DIR__, null);
  1320. }
  1321. /**
  1322. * @throws ZipException
  1323. */
  1324. public function testAddFilesFromGlobRecursiveEmptyPattern()
  1325. {
  1326. $this->setExpectedException(InvalidArgumentException::class, 'The glob pattern is not specified');
  1327. $zipFile = new ZipFile();
  1328. $zipFile->addFilesFromGlobRecursive(__DIR__, '');
  1329. }
  1330. /**
  1331. * @throws ZipException
  1332. */
  1333. public function testAddFilesFromRegexDirectoryNull()
  1334. {
  1335. $this->setExpectedException(InvalidArgumentException::class, 'The input directory is not specified');
  1336. $zipFile = new ZipFile();
  1337. $zipFile->addFilesFromRegex(null, '~\.png$~i');
  1338. }
  1339. /**
  1340. * @throws ZipException
  1341. */
  1342. public function testAddFilesFromRegexDirectoryEmpty()
  1343. {
  1344. $this->setExpectedException(InvalidArgumentException::class, 'The input directory is not specified');
  1345. $zipFile = new ZipFile();
  1346. $zipFile->addFilesFromRegex('', '~\.png$~i');
  1347. }
  1348. /**
  1349. * @throws ZipException
  1350. */
  1351. public function testAddFilesFromRegexCantExists()
  1352. {
  1353. $this->setExpectedException(InvalidArgumentException::class, 'does not exist');
  1354. $zipFile = new ZipFile();
  1355. $zipFile->addFilesFromRegex('path/to/path', '~\.png$~i');
  1356. }
  1357. /**
  1358. * @throws ZipException
  1359. */
  1360. public function testAddFilesFromRegexNullPattern()
  1361. {
  1362. $this->setExpectedException(InvalidArgumentException::class, 'The regex pattern is not specified');
  1363. $zipFile = new ZipFile();
  1364. $zipFile->addFilesFromRegex(__DIR__, null);
  1365. }
  1366. /**
  1367. * @throws ZipException
  1368. */
  1369. public function testAddFilesFromRegexEmptyPattern()
  1370. {
  1371. $this->setExpectedException(InvalidArgumentException::class, 'The regex pattern is not specified');
  1372. $zipFile = new ZipFile();
  1373. $zipFile->addFilesFromRegex(__DIR__, '');
  1374. }
  1375. /**
  1376. * @throws ZipException
  1377. */
  1378. public function testAddFilesFromRegexRecursiveDirectoryNull()
  1379. {
  1380. $this->setExpectedException(InvalidArgumentException::class, 'The input directory is not specified');
  1381. $zipFile = new ZipFile();
  1382. $zipFile->addFilesFromRegexRecursive(null, '~\.png$~i');
  1383. }
  1384. /**
  1385. * @throws ZipException
  1386. */
  1387. public function testAddFilesFromRegexRecursiveEmpty()
  1388. {
  1389. $this->setExpectedException(InvalidArgumentException::class, 'The input directory is not specified');
  1390. $zipFile = new ZipFile();
  1391. $zipFile->addFilesFromRegexRecursive('', '~\.png$~i');
  1392. }
  1393. /**
  1394. * @throws ZipException
  1395. */
  1396. public function testAddFilesFromRegexRecursiveCantExists()
  1397. {
  1398. $this->setExpectedException(InvalidArgumentException::class, 'does not exist');
  1399. $zipFile = new ZipFile();
  1400. $zipFile->addFilesFromGlobRecursive('path/to/path', '~\.png$~i');
  1401. }
  1402. /**
  1403. * @throws ZipException
  1404. */
  1405. public function testAddFilesFromRegexRecursiveNullPattern()
  1406. {
  1407. $this->setExpectedException(InvalidArgumentException::class, 'The regex pattern is not specified');
  1408. $zipFile = new ZipFile();
  1409. $zipFile->addFilesFromRegexRecursive(__DIR__, null);
  1410. }
  1411. /**
  1412. * @throws ZipException
  1413. */
  1414. public function testAddFilesFromRegexRecursiveEmptyPattern()
  1415. {
  1416. $this->setExpectedException(InvalidArgumentException::class, 'The regex pattern is not specified');
  1417. $zipFile = new ZipFile();
  1418. $zipFile->addFilesFromRegexRecursive(__DIR__, '');
  1419. }
  1420. /**
  1421. * @throws ZipException
  1422. */
  1423. public function testSaveAsStreamBadStream()
  1424. {
  1425. $this->setExpectedException(InvalidArgumentException::class, 'handle is not resource');
  1426. $zipFile = new ZipFile();
  1427. /** @noinspection PhpParamsInspection */
  1428. $zipFile->saveAsStream('bad stream');
  1429. }
  1430. /**
  1431. * @throws ZipException
  1432. */
  1433. public function testSaveAsFileNotWritable()
  1434. {
  1435. $this->setExpectedException(InvalidArgumentException::class, 'can not open from write');
  1436. if (static::skipTestForRootUser()) {
  1437. return;
  1438. }
  1439. static::assertTrue(mkdir($this->outputDirname, 0444, true));
  1440. static::assertTrue(chmod($this->outputDirname, 0444));
  1441. $this->outputFilename = $this->outputDirname . \DIRECTORY_SEPARATOR . basename($this->outputFilename);
  1442. $zipFile = new ZipFile();
  1443. $zipFile->saveAsFile($this->outputFilename);
  1444. }
  1445. /**
  1446. * Test `ZipFile` implemented \ArrayAccess, \Countable and |iterator.
  1447. *
  1448. * @throws ZipException
  1449. * @throws \Exception
  1450. */
  1451. public function testZipFileArrayAccessAndCountableAndIterator()
  1452. {
  1453. $files = [];
  1454. $numFiles = mt_rand(20, 100);
  1455. for ($i = 0; $i < $numFiles; $i++) {
  1456. $files['file' . $i . '.txt'] = random_bytes(255);
  1457. }
  1458. $compressionMethods = [ZipCompressionMethod::STORED, ZipCompressionMethod::DEFLATED];
  1459. if (\extension_loaded('bz2')) {
  1460. $compressionMethods[] = ZipCompressionMethod::BZIP2;
  1461. }
  1462. $zipFile = new ZipFile();
  1463. $zipFile->setCompressionLevel(ZipCompressionLevel::SUPER_FAST);
  1464. $i = 0;
  1465. $countMethods = \count($compressionMethods);
  1466. foreach ($files as $entryName => $content) {
  1467. $compressionMethod = $compressionMethods[$i++ % $countMethods];
  1468. $zipFile->addFromString($entryName, $content, $compressionMethod);
  1469. }
  1470. $zipFile->saveAsFile($this->outputFilename);
  1471. $zipFile->close();
  1472. static::assertCorrectZipArchive($this->outputFilename);
  1473. $zipFile->openFile($this->outputFilename);
  1474. // Test \Countable
  1475. static::assertSame($zipFile->count(), $numFiles);
  1476. static::assertSame(\count($zipFile), $numFiles);
  1477. // Test \ArrayAccess
  1478. reset($files);
  1479. foreach ($zipFile as $entryName => $content) {
  1480. static::assertSame($entryName, key($files));
  1481. static::assertSame($content, current($files));
  1482. next($files);
  1483. }
  1484. // Test \Iterator
  1485. reset($files);
  1486. $iterator = new \ArrayIterator($zipFile);
  1487. $iterator->rewind();
  1488. while ($iterator->valid()) {
  1489. $key = $iterator->key();
  1490. $value = $iterator->current();
  1491. static::assertSame($key, key($files));
  1492. static::assertSame($value, current($files));
  1493. next($files);
  1494. $iterator->next();
  1495. }
  1496. $zipFile->close();
  1497. $zipFile = new ZipFile();
  1498. $zipFile['file1.txt'] = 'content 1';
  1499. $zipFile['dir/file2.txt'] = 'content 1';
  1500. $zipFile['dir/empty dir/'] = null;
  1501. $zipFile->saveAsFile($this->outputFilename);
  1502. $zipFile->close();
  1503. static::assertCorrectZipArchive($this->outputFilename);
  1504. $zipFile->openFile($this->outputFilename);
  1505. static::assertTrue(isset($zipFile['file1.txt']));
  1506. static::assertTrue(isset($zipFile['dir/file2.txt']));
  1507. static::assertTrue(isset($zipFile['dir/empty dir/']));
  1508. static::assertFalse(isset($zipFile['dir/empty dir/2/']));
  1509. $zipFile['dir/empty dir/2/'] = null;
  1510. unset($zipFile['dir/file2.txt'], $zipFile['dir/empty dir/']);
  1511. $zipFile->saveAsFile($this->outputFilename);
  1512. $zipFile->close();
  1513. static::assertCorrectZipArchive($this->outputFilename);
  1514. $zipFile->openFile($this->outputFilename);
  1515. static::assertTrue(isset($zipFile['file1.txt']));
  1516. static::assertFalse(isset($zipFile['dir/file2.txt']));
  1517. static::assertFalse(isset($zipFile['dir/empty dir/']));
  1518. static::assertTrue(isset($zipFile['dir/empty dir/2/']));
  1519. $zipFile->close();
  1520. }
  1521. /**
  1522. * @throws ZipException
  1523. */
  1524. public function testArrayAccessAddFile()
  1525. {
  1526. $entryName = 'path/to/file.dat';
  1527. $entryNameStream = 'path/to/' . basename(__FILE__);
  1528. $zipFile = new ZipFile();
  1529. $zipFile[$entryName] = new \SplFileInfo(__FILE__);
  1530. $zipFile[$entryNameStream] = fopen(__FILE__, 'rb');
  1531. $zipFile->saveAsFile($this->outputFilename);
  1532. $zipFile->close();
  1533. static::assertCorrectZipArchive($this->outputFilename);
  1534. $zipFile->openFile($this->outputFilename);
  1535. static::assertSame(\count($zipFile), 2);
  1536. static::assertTrue(isset($zipFile[$entryName]));
  1537. static::assertTrue(isset($zipFile[$entryNameStream]));
  1538. static::assertSame($zipFile[$entryName], file_get_contents(__FILE__));
  1539. static::assertSame($zipFile[$entryNameStream], file_get_contents(__FILE__));
  1540. $zipFile->close();
  1541. }
  1542. /**
  1543. * @throws ZipEntryNotFoundException
  1544. * @throws ZipException
  1545. * @throws \Exception
  1546. */
  1547. public function testUnknownCompressionMethod()
  1548. {
  1549. $zipFile = new ZipFile();
  1550. $zipFile->addFromString('file', 'content', ZipEntry::UNKNOWN);
  1551. $zipFile->addFromString('file2', base64_encode(random_bytes(512)), ZipEntry::UNKNOWN);
  1552. static::assertSame($zipFile->getEntryInfo('file')->getMethodName(), 'Stored');
  1553. static::assertSame($zipFile->getEntryInfo('file2')->getMethodName(), 'Deflated');
  1554. $zipFile->saveAsFile($this->outputFilename);
  1555. $zipFile->close();
  1556. $zipFile->openFile($this->outputFilename);
  1557. static::assertSame($zipFile->getEntryInfo('file')->getMethodName(), 'Stored');
  1558. static::assertSame($zipFile->getEntryInfo('file2')->getMethodName(), 'Deflated');
  1559. $zipFile->close();
  1560. }
  1561. /**
  1562. * @throws ZipException
  1563. */
  1564. public function testAddEmptyDirNullName()
  1565. {
  1566. $this->setExpectedException(InvalidArgumentException::class, 'Dir name is null');
  1567. $zipFile = new ZipFile();
  1568. $zipFile->addEmptyDir(null);
  1569. }
  1570. /**
  1571. * @throws ZipException
  1572. */
  1573. public function testAddEmptyDirEmptyName()
  1574. {
  1575. $this->setExpectedException(InvalidArgumentException::class, 'Empty dir name');
  1576. $zipFile = new ZipFile();
  1577. $zipFile->addEmptyDir('');
  1578. }
  1579. public function testNotFoundEntry()
  1580. {
  1581. $this->setExpectedException(ZipEntryNotFoundException::class, '"bad entry name"');
  1582. $zipFile = new ZipFile();
  1583. $zipFile['bad entry name'];
  1584. }
  1585. /**
  1586. * Test rewrite input file.
  1587. *
  1588. * @throws ZipException
  1589. */
  1590. public function testRewriteFile()
  1591. {
  1592. $zipFile = new ZipFile();
  1593. $zipFile['file'] = 'content';
  1594. $zipFile['file2'] = 'content2';
  1595. static::assertSame(\count($zipFile), 2);
  1596. $zipFile
  1597. ->saveAsFile($this->outputFilename)
  1598. ->close()
  1599. ;
  1600. $md5file = md5_file($this->outputFilename);
  1601. $zipFile->openFile($this->outputFilename);
  1602. static::assertSame(\count($zipFile), 2);
  1603. static::assertTrue(isset($zipFile['file']));
  1604. static::assertTrue(isset($zipFile['file2']));
  1605. $zipFile['file3'] = 'content3';
  1606. static::assertSame(\count($zipFile), 3);
  1607. $zipFile = $zipFile->rewrite();
  1608. static::assertSame(\count($zipFile), 3);
  1609. static::assertTrue(isset($zipFile['file']));
  1610. static::assertTrue(isset($zipFile['file2']));
  1611. static::assertTrue(isset($zipFile['file3']));
  1612. $zipFile->close();
  1613. static::assertNotSame(md5_file($this->outputFilename), $md5file);
  1614. }
  1615. /**
  1616. * Test rewrite for string.
  1617. *
  1618. * @throws ZipException
  1619. */
  1620. public function testRewriteString()
  1621. {
  1622. $this->setExpectedException(ZipException::class, 'Overwrite is only supported for open local files');
  1623. $zipFile = new ZipFile();
  1624. $zipFile['file'] = 'content';
  1625. $zipFile->saveAsFile($this->outputFilename);
  1626. $zipFile->close();
  1627. $zipFile->openFromString(file_get_contents($this->outputFilename));
  1628. $zipFile['file2'] = 'content 2';
  1629. $zipFile->rewrite();
  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. /**
  2010. * @throws ZipException
  2011. */
  2012. public function testRenameWithRecompressData()
  2013. {
  2014. $entryName = 'file.txt';
  2015. $newEntryName = 'rename_file.txt';
  2016. $contents = str_repeat('Test' . \PHP_EOL, 1024);
  2017. $zipFile = new ZipFile();
  2018. $zipFile->addFromString($entryName, $contents, ZipCompressionMethod::DEFLATED);
  2019. $zipFile->saveAsFile($this->outputFilename);
  2020. $zipFile->close();
  2021. self::assertCorrectZipArchive($this->outputFilename);
  2022. $zipFile->openFile($this->outputFilename);
  2023. $zipFile->rename($entryName, $newEntryName);
  2024. $zipFile->setCompressionMethodEntry($newEntryName, ZipCompressionMethod::STORED);
  2025. $zipFile->saveAsFile($this->outputFilename);
  2026. $zipFile->close();
  2027. self::assertCorrectZipArchive($this->outputFilename);
  2028. $zipFile->openFile($this->outputFilename);
  2029. static::assertSame($zipFile->getEntry($newEntryName)->getCompressionMethod(), ZipCompressionMethod::STORED);
  2030. $zipFile->close();
  2031. }
  2032. /**
  2033. * @throws ZipEntryNotFoundException
  2034. * @throws ZipException
  2035. */
  2036. public function testCloneZipContainerInZipWriter()
  2037. {
  2038. $zipFile = new ZipFile();
  2039. $zipFile['file 1'] = 'contents';
  2040. $zipEntryBeforeWrite = $zipFile->getEntry('file 1');
  2041. $zipFile->saveAsFile($this->outputFilename);
  2042. $zipAfterBeforeWrite = $zipFile->getEntry('file 1');
  2043. static::assertSame($zipAfterBeforeWrite, $zipEntryBeforeWrite);
  2044. $zipFile->close();
  2045. }
  2046. /**
  2047. * @throws ZipException
  2048. */
  2049. public function testMultiSave()
  2050. {
  2051. $zipFile = new ZipFile();
  2052. $zipFile['file 1'] = 'contents';
  2053. for ($i = 0; $i < 10; $i++) {
  2054. $zipFile->saveAsFile($this->outputFilename);
  2055. self::assertCorrectZipArchive($this->outputFilename);
  2056. }
  2057. $zipFile->close();
  2058. }
  2059. /**
  2060. * @throws ZipEntryNotFoundException
  2061. * @throws ZipException
  2062. */
  2063. public function testNoData()
  2064. {
  2065. $this->setExpectedException(ZipException::class, 'No data for zip entry file');
  2066. $entryName = 'file';
  2067. $zipFile = new ZipFile();
  2068. try {
  2069. $zipFile[$entryName] = '';
  2070. $zipEntry = $zipFile->getEntry($entryName);
  2071. $zipEntry->setData(null);
  2072. $zipFile->getEntryContents($entryName);
  2073. } finally {
  2074. $zipFile->close();
  2075. }
  2076. }
  2077. /**
  2078. * @throws ZipEntryNotFoundException
  2079. * @throws ZipException
  2080. */
  2081. public function testReplaceEntryContentsByFile()
  2082. {
  2083. $entryName = basename(__FILE__);
  2084. $zipFile = new ZipFile();
  2085. $zipFile[$entryName] = 'contents';
  2086. $zipFile->saveAsFile($this->outputFilename);
  2087. $zipFile->close();
  2088. $zipFile->openFile($this->outputFilename);
  2089. $entry = $zipFile->getEntry($entryName);
  2090. $data = new ZipFileData($entry, new \SplFileInfo(__FILE__));
  2091. $entry->setData($data);
  2092. $zipFile->saveAsFile($this->outputFilename);
  2093. $zipFile->close();
  2094. self::assertCorrectZipArchive($this->outputFilename);
  2095. $zipFile->openFile($this->outputFilename);
  2096. static::assertSame(
  2097. $zipFile->getEntryContents($entryName),
  2098. file_get_contents(__FILE__)
  2099. );
  2100. $zipFile->close();
  2101. }
  2102. }