2
0

ZipFileTest.php 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514
  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. $zipFile = new ZipFile();
  1623. $zipFile['file'] = 'content';
  1624. $zipFile['file2'] = 'content2';
  1625. $zipFile->saveAsFile($this->outputFilename);
  1626. $zipFile->close();
  1627. $zipFile->openFromString(file_get_contents($this->outputFilename));
  1628. static::assertSame(\count($zipFile), 2);
  1629. static::assertTrue(isset($zipFile['file']));
  1630. static::assertTrue(isset($zipFile['file2']));
  1631. $zipFile['file3'] = 'content3';
  1632. $zipFile = $zipFile->rewrite();
  1633. static::assertSame(\count($zipFile), 3);
  1634. static::assertTrue(isset($zipFile['file']));
  1635. static::assertTrue(isset($zipFile['file2']));
  1636. static::assertTrue(isset($zipFile['file3']));
  1637. $zipFile->close();
  1638. }
  1639. /**
  1640. * @throws ZipException
  1641. */
  1642. public function testRewriteNullStream()
  1643. {
  1644. $this->setExpectedException(ZipException::class, 'input stream is null');
  1645. $zipFile = new ZipFile();
  1646. $zipFile->rewrite();
  1647. }
  1648. /**
  1649. * @throws ZipException
  1650. */
  1651. public function testFilename0()
  1652. {
  1653. $zipFile = new ZipFile();
  1654. $zipFile[0] = 0;
  1655. static::assertTrue(isset($zipFile[0]));
  1656. static::assertTrue(isset($zipFile['0']));
  1657. static::assertCount(1, $zipFile);
  1658. $zipFile
  1659. ->saveAsFile($this->outputFilename)
  1660. ->close()
  1661. ;
  1662. static::assertCorrectZipArchive($this->outputFilename);
  1663. $zipFile->openFile($this->outputFilename);
  1664. static::assertTrue(isset($zipFile[0]));
  1665. static::assertTrue(isset($zipFile['0']));
  1666. static::assertSame($zipFile['0'], '0');
  1667. static::assertCount(1, $zipFile);
  1668. $zipFile->close();
  1669. static::assertTrue(unlink($this->outputFilename));
  1670. $zipFile = new ZipFile();
  1671. $zipFile->addFromString(0, 0);
  1672. static::assertTrue(isset($zipFile[0]));
  1673. static::assertTrue(isset($zipFile['0']));
  1674. static::assertCount(1, $zipFile);
  1675. $zipFile
  1676. ->saveAsFile($this->outputFilename)
  1677. ->close()
  1678. ;
  1679. static::assertCorrectZipArchive($this->outputFilename);
  1680. }
  1681. /**
  1682. * @throws ZipException
  1683. */
  1684. public function testPsrResponse()
  1685. {
  1686. $zipFile = new ZipFile();
  1687. for ($i = 0; $i < 10; $i++) {
  1688. $zipFile[$i] = $i;
  1689. }
  1690. $filename = 'file.jar';
  1691. $response = $zipFile->outputAsResponse(new Response(), $filename);
  1692. static::assertInstanceOf(ResponseInterface::class, $response);
  1693. static::assertSame('application/java-archive', $response->getHeaderLine('content-type'));
  1694. static::assertSame('attachment; filename="file.jar"', $response->getHeaderLine('content-disposition'));
  1695. }
  1696. /**
  1697. * @dataProvider provideCompressionLevels
  1698. *
  1699. * @param int $compressionLevel
  1700. *
  1701. * @throws ZipEntryNotFoundException
  1702. * @throws ZipException
  1703. * @throws \Exception
  1704. */
  1705. public function testCompressionLevel($compressionLevel)
  1706. {
  1707. $fileContent = random_bytes(512);
  1708. $entryName = 'file.txt';
  1709. $zipFile = new ZipFile();
  1710. $zipFile
  1711. ->addFromString($entryName, $fileContent, ZipCompressionMethod::DEFLATED)
  1712. ->setCompressionLevelEntry($entryName, $compressionLevel)
  1713. ->saveAsFile($this->outputFilename)
  1714. ->close()
  1715. ;
  1716. static::assertCorrectZipArchive($this->outputFilename);
  1717. $zipFile->openFile($this->outputFilename);
  1718. static::assertSame($zipFile->getEntryContents($entryName), $fileContent);
  1719. static::assertSame($zipFile->getEntry($entryName)->getCompressionLevel(), $compressionLevel);
  1720. static::assertSame($zipFile->getEntryInfo($entryName)->getCompressionLevel(), $compressionLevel);
  1721. $zipFile->close();
  1722. }
  1723. /**
  1724. * @return array
  1725. */
  1726. public function provideCompressionLevels()
  1727. {
  1728. return [
  1729. [ZipCompressionLevel::MAXIMUM],
  1730. [ZipCompressionLevel::NORMAL],
  1731. [ZipCompressionLevel::FAST],
  1732. [ZipCompressionLevel::SUPER_FAST],
  1733. ];
  1734. }
  1735. /**
  1736. * @throws ZipException
  1737. */
  1738. public function testInvalidCompressionLevel()
  1739. {
  1740. $this->setExpectedException(InvalidArgumentException::class, 'Invalid compression level');
  1741. $zipFile = new ZipFile();
  1742. $zipFile->addFromString('file', 'content');
  1743. $zipFile->setCompressionLevel(15);
  1744. }
  1745. /**
  1746. * @throws ZipException
  1747. */
  1748. public function testInvalidCompressionLevelEntry()
  1749. {
  1750. $this->setExpectedException(InvalidArgumentException::class, 'Invalid compression level');
  1751. $zipFile = new ZipFile();
  1752. $zipFile->addFromString('file', 'content');
  1753. $zipFile->setCompressionLevelEntry('file', 15);
  1754. }
  1755. /**
  1756. * @throws ZipException
  1757. */
  1758. public function testCompressionGlobal()
  1759. {
  1760. $zipFile = new ZipFile();
  1761. for ($i = 0; $i < 10; $i++) {
  1762. $zipFile->addFromString('file' . $i, 'content', ZipCompressionMethod::DEFLATED);
  1763. }
  1764. $zipFile
  1765. ->setCompressionLevel(ZipCompressionLevel::SUPER_FAST)
  1766. ->saveAsFile($this->outputFilename)
  1767. ->close()
  1768. ;
  1769. static::assertCorrectZipArchive($this->outputFilename);
  1770. $zipFile->openFile($this->outputFilename);
  1771. $infoList = $zipFile->getAllInfo();
  1772. array_walk(
  1773. $infoList,
  1774. function (ZipInfo $zipInfo) {
  1775. $this->assertSame($zipInfo->getCompressionLevel(), ZipCompressionLevel::SUPER_FAST);
  1776. }
  1777. );
  1778. $zipFile->close();
  1779. }
  1780. /**
  1781. * @throws ZipEntryNotFoundException
  1782. * @throws ZipException
  1783. */
  1784. public function testCompressionMethodEntry()
  1785. {
  1786. $zipFile = new ZipFile();
  1787. $zipFile->addFromString('file', 'content', ZipCompressionMethod::STORED);
  1788. $zipFile->saveAsFile($this->outputFilename);
  1789. $zipFile->close();
  1790. $zipFile->openFile($this->outputFilename);
  1791. static::assertSame($zipFile->getEntryInfo('file')->getMethodName(), 'Stored');
  1792. $zipFile->setCompressionMethodEntry('file', ZipCompressionMethod::DEFLATED);
  1793. static::assertSame($zipFile->getEntryInfo('file')->getMethodName(), 'Deflated');
  1794. $zipFile->rewrite();
  1795. static::assertSame($zipFile->getEntryInfo('file')->getMethodName(), 'Deflated');
  1796. }
  1797. /**
  1798. * @throws ZipException
  1799. */
  1800. public function testInvalidCompressionMethodEntry()
  1801. {
  1802. $this->setExpectedException(
  1803. ZipUnsupportMethodException::class,
  1804. 'Compression method 99 (AES Encryption) is not supported.'
  1805. );
  1806. $zipFile = new ZipFile();
  1807. $zipFile->addFromString('file', 'content', ZipCompressionMethod::STORED);
  1808. $zipFile->setCompressionMethodEntry('file', 99);
  1809. $zipFile->outputAsString();
  1810. }
  1811. /**
  1812. * @throws ZipException
  1813. */
  1814. public function testUnchangeAll()
  1815. {
  1816. $zipFile = new ZipFile();
  1817. for ($i = 0; $i < 10; $i++) {
  1818. $zipFile[$i] = $i;
  1819. }
  1820. $zipFile->setArchiveComment('comment');
  1821. static::assertCount(10, $zipFile);
  1822. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1823. $zipFile->saveAsFile($this->outputFilename);
  1824. $zipFile->unchangeAll();
  1825. static::assertCount(0, $zipFile);
  1826. static::assertNull($zipFile->getArchiveComment());
  1827. $zipFile->close();
  1828. $zipFile->openFile($this->outputFilename);
  1829. static::assertCount(10, $zipFile);
  1830. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1831. for ($i = 10; $i < 100; $i++) {
  1832. $zipFile[$i] = $i;
  1833. }
  1834. $zipFile->setArchiveComment('comment 2');
  1835. static::assertCount(100, $zipFile);
  1836. static::assertSame($zipFile->getArchiveComment(), 'comment 2');
  1837. $zipFile->unchangeAll();
  1838. static::assertCount(10, $zipFile);
  1839. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1840. $zipFile->close();
  1841. }
  1842. /**
  1843. * @throws ZipException
  1844. */
  1845. public function testUnchangeArchiveComment()
  1846. {
  1847. $zipFile = new ZipFile();
  1848. for ($i = 0; $i < 10; $i++) {
  1849. $zipFile[$i] = $i;
  1850. }
  1851. $zipFile->setArchiveComment('comment');
  1852. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1853. $zipFile->saveAsFile($this->outputFilename);
  1854. $zipFile->unchangeArchiveComment();
  1855. static::assertNull($zipFile->getArchiveComment());
  1856. $zipFile->close();
  1857. $zipFile->openFile($this->outputFilename);
  1858. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1859. $zipFile->setArchiveComment('comment 2');
  1860. static::assertSame($zipFile->getArchiveComment(), 'comment 2');
  1861. $zipFile->unchangeArchiveComment();
  1862. static::assertSame($zipFile->getArchiveComment(), 'comment');
  1863. $zipFile->close();
  1864. }
  1865. /**
  1866. * @throws ZipEntryNotFoundException
  1867. * @throws ZipException
  1868. */
  1869. public function testUnchangeEntry()
  1870. {
  1871. $zipFile = new ZipFile();
  1872. $zipFile['file 1'] = 'content 1';
  1873. $zipFile['file 2'] = 'content 2';
  1874. $zipFile
  1875. ->saveAsFile($this->outputFilename)
  1876. ->close()
  1877. ;
  1878. $zipFile->openFile($this->outputFilename);
  1879. $zipFile['file 1'] = 'modify content 1';
  1880. $zipFile->setPasswordEntry('file 1', 'password');
  1881. static::assertSame($zipFile['file 1'], 'modify content 1');
  1882. static::assertTrue($zipFile->getEntryInfo('file 1')->isEncrypted());
  1883. static::assertSame($zipFile['file 2'], 'content 2');
  1884. static::assertFalse($zipFile->getEntryInfo('file 2')->isEncrypted());
  1885. $zipFile->unchangeEntry('file 1');
  1886. static::assertSame($zipFile['file 1'], 'content 1');
  1887. static::assertFalse($zipFile->getEntryInfo('file 1')->isEncrypted());
  1888. static::assertSame($zipFile['file 2'], 'content 2');
  1889. static::assertFalse($zipFile->getEntryInfo('file 2')->isEncrypted());
  1890. $zipFile->close();
  1891. }
  1892. /**
  1893. * @runInSeparateProcess
  1894. *
  1895. * @dataProvider provideOutputAsAttachment
  1896. *
  1897. * @param string $zipFilename
  1898. * @param string|null $mimeType
  1899. * @param string $expectedMimeType
  1900. * @param bool $attachment
  1901. * @param string $expectedAttachment
  1902. *
  1903. * @throws ZipException
  1904. */
  1905. public function testOutputAsAttachment($zipFilename, $mimeType, $expectedMimeType, $attachment, $expectedAttachment)
  1906. {
  1907. $zipFile = new ZipFile();
  1908. $file1Contents = 'content 1';
  1909. $zipFile['file 1'] = $file1Contents;
  1910. ob_start();
  1911. $zipFile->outputAsAttachment($zipFilename, $mimeType, $attachment);
  1912. $zipContents = ob_get_clean();
  1913. $zipFile->close();
  1914. $length = \strlen($zipContents);
  1915. static::assertTrue($length > 0);
  1916. $zipFile->openFromString($zipContents);
  1917. static::assertSame($zipFile['file 1'], $file1Contents);
  1918. $zipFile->close();
  1919. if (\function_exists('xdebug_get_headers')) {
  1920. $expectedHeaders = [
  1921. 'Content-Disposition: ' . $expectedAttachment . '; filename="' . $zipFilename . '"',
  1922. 'Content-Type: ' . $expectedMimeType,
  1923. 'Content-Length: ' . $length,
  1924. ];
  1925. /** @noinspection ForgottenDebugOutputInspection */
  1926. /** @noinspection PhpComposerExtensionStubsInspection */
  1927. static::assertSame($expectedHeaders, xdebug_get_headers());
  1928. }
  1929. }
  1930. /**
  1931. * @return array
  1932. */
  1933. public function provideOutputAsAttachment()
  1934. {
  1935. return [
  1936. ['file.zip', null, 'application/zip', true, 'attachment'],
  1937. ['file.zip', 'application/x-zip', 'application/x-zip', false, 'inline'],
  1938. ['file.apk', null, 'application/vnd.android.package-archive', true, 'attachment'],
  1939. ];
  1940. }
  1941. /**
  1942. * @dataProvider provideGetEntryStream
  1943. *
  1944. * @param ZipFile $zipFile
  1945. * @param string $entryName
  1946. * @param string $contents
  1947. *
  1948. * @throws ZipEntryNotFoundException
  1949. * @throws ZipException
  1950. */
  1951. public function testReopenEntryStream(ZipFile $zipFile, $entryName, $contents)
  1952. {
  1953. for ($i = 0; $i < 2; $i++) {
  1954. $fp = $zipFile->getEntryStream($entryName);
  1955. static::assertInternalType('resource', $fp);
  1956. static::assertSame(stream_get_contents($fp), $contents);
  1957. fclose($fp);
  1958. }
  1959. $zipFile->close();
  1960. }
  1961. /**
  1962. * @throws \Exception
  1963. *
  1964. * @return array
  1965. */
  1966. public function provideGetEntryStream()
  1967. {
  1968. $entryName = 'entry';
  1969. $contents = random_bytes(1024);
  1970. $zipFileSpl = new ZipFile();
  1971. $zipFileSpl->addSplFile(new \SplFileInfo(__FILE__), $entryName);
  1972. return [
  1973. [(new ZipFile())->addFromString($entryName, $contents), $entryName, $contents],
  1974. [(new ZipFile())->addFile(__FILE__, $entryName), $entryName, file_get_contents(__FILE__)],
  1975. [
  1976. (new ZipFile())->addFromStream(fopen(__FILE__, 'rb'), $entryName),
  1977. $entryName,
  1978. file_get_contents(__FILE__),
  1979. ],
  1980. [$zipFileSpl, $entryName, file_get_contents(__FILE__)],
  1981. ];
  1982. }
  1983. /**
  1984. * @throws ZipException
  1985. */
  1986. public function testGetEntries()
  1987. {
  1988. $zipFile = new ZipFile();
  1989. for ($i = 0; $i < 100; $i++) {
  1990. $zipFile->addFromString($i . '.txt', 'contents ' . $i);
  1991. }
  1992. $zipFile->saveAsFile($this->outputFilename);
  1993. $zipFile->close();
  1994. $zipFile->openFile($this->outputFilename);
  1995. $zipEntries = $zipFile->getEntries();
  1996. static::assertCount(100, $zipEntries);
  1997. foreach ($zipEntries as $zipEntry) {
  1998. static::assertInstanceOf(ZipEntry::class, $zipEntry);
  1999. static::assertNotSame($zipEntry->getDosTime(), 0);
  2000. $zipEntry->setDosTime(0);
  2001. $zipEntry->setCreatedOS(ZipPlatform::OS_DOS);
  2002. $zipEntry->setExtractedOS(ZipPlatform::OS_DOS);
  2003. $zipEntry->setInternalAttributes(1);
  2004. $zipEntry->setExternalAttributes(0);
  2005. }
  2006. $zipFile->rewrite();
  2007. self::assertCorrectZipArchive($this->outputFilename);
  2008. foreach ($zipFile->getEntries() as $zipEntry) {
  2009. static::assertSame($zipEntry->getDosTime(), 0);
  2010. static::assertSame($zipEntry->getExtractedOS(), ZipPlatform::OS_DOS);
  2011. static::assertSame($zipEntry->getCreatedOS(), ZipPlatform::OS_DOS);
  2012. static::assertSame($zipEntry->getInternalAttributes(), 1);
  2013. static::assertSame($zipEntry->getExternalAttributes(), 0);
  2014. }
  2015. $zipFile->close();
  2016. }
  2017. /**
  2018. * @throws ZipException
  2019. */
  2020. public function testRenameWithRecompressData()
  2021. {
  2022. $entryName = 'file.txt';
  2023. $newEntryName = 'rename_file.txt';
  2024. $contents = str_repeat('Test' . \PHP_EOL, 1024);
  2025. $zipFile = new ZipFile();
  2026. $zipFile->addFromString($entryName, $contents, ZipCompressionMethod::DEFLATED);
  2027. $zipFile->saveAsFile($this->outputFilename);
  2028. $zipFile->close();
  2029. self::assertCorrectZipArchive($this->outputFilename);
  2030. $zipFile->openFile($this->outputFilename);
  2031. $zipFile->rename($entryName, $newEntryName);
  2032. $zipFile->setCompressionMethodEntry($newEntryName, ZipCompressionMethod::STORED);
  2033. $zipFile->saveAsFile($this->outputFilename);
  2034. $zipFile->close();
  2035. self::assertCorrectZipArchive($this->outputFilename);
  2036. $zipFile->openFile($this->outputFilename);
  2037. static::assertSame($zipFile->getEntry($newEntryName)->getCompressionMethod(), ZipCompressionMethod::STORED);
  2038. $zipFile->close();
  2039. }
  2040. /**
  2041. * @throws ZipEntryNotFoundException
  2042. * @throws ZipException
  2043. */
  2044. public function testCloneZipContainerInZipWriter()
  2045. {
  2046. $zipFile = new ZipFile();
  2047. $zipFile['file 1'] = 'contents';
  2048. $zipEntryBeforeWrite = $zipFile->getEntry('file 1');
  2049. $zipFile->saveAsFile($this->outputFilename);
  2050. $zipAfterBeforeWrite = $zipFile->getEntry('file 1');
  2051. static::assertSame($zipAfterBeforeWrite, $zipEntryBeforeWrite);
  2052. $zipFile->close();
  2053. }
  2054. /**
  2055. * @throws ZipException
  2056. */
  2057. public function testMultiSave()
  2058. {
  2059. $zipFile = new ZipFile();
  2060. $zipFile['file 1'] = 'contents';
  2061. for ($i = 0; $i < 10; $i++) {
  2062. $zipFile->saveAsFile($this->outputFilename);
  2063. self::assertCorrectZipArchive($this->outputFilename);
  2064. }
  2065. $zipFile->close();
  2066. }
  2067. /**
  2068. * @throws ZipEntryNotFoundException
  2069. * @throws ZipException
  2070. */
  2071. public function testNoData()
  2072. {
  2073. $this->setExpectedException(ZipException::class, 'No data for zip entry file');
  2074. $entryName = 'file';
  2075. $zipFile = new ZipFile();
  2076. try {
  2077. $zipFile[$entryName] = '';
  2078. $zipEntry = $zipFile->getEntry($entryName);
  2079. $zipEntry->setData(null);
  2080. $zipFile->getEntryContents($entryName);
  2081. } finally {
  2082. $zipFile->close();
  2083. }
  2084. }
  2085. /**
  2086. * @throws ZipEntryNotFoundException
  2087. * @throws ZipException
  2088. */
  2089. public function testReplaceEntryContentsByFile()
  2090. {
  2091. $entryName = basename(__FILE__);
  2092. $zipFile = new ZipFile();
  2093. $zipFile[$entryName] = 'contents';
  2094. $zipFile->saveAsFile($this->outputFilename);
  2095. $zipFile->close();
  2096. $zipFile->openFile($this->outputFilename);
  2097. $entry = $zipFile->getEntry($entryName);
  2098. $data = new ZipFileData($entry, new \SplFileInfo(__FILE__));
  2099. $entry->setData($data);
  2100. $zipFile->saveAsFile($this->outputFilename);
  2101. $zipFile->close();
  2102. self::assertCorrectZipArchive($this->outputFilename);
  2103. $zipFile->openFile($this->outputFilename);
  2104. static::assertSame(
  2105. $zipFile->getEntryContents($entryName),
  2106. file_get_contents(__FILE__)
  2107. );
  2108. $zipFile->close();
  2109. }
  2110. }