ZipFileTest.php 74 KB

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