ZipFileTest.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  1. <?php
  2. namespace PhpZip;
  3. use PhpZip\Exception\ZipAuthenticationException;
  4. use PhpZip\Model\ZipEntry;
  5. use PhpZip\Util\CryptoUtil;
  6. use PhpZip\Util\FilesUtil;
  7. /**
  8. * ZipFile test
  9. */
  10. class ZipFileTest extends ZipTestCase
  11. {
  12. /**
  13. * @var string
  14. */
  15. private $outputFilename;
  16. /**
  17. * Before test
  18. */
  19. protected function setUp()
  20. {
  21. parent::setUp();
  22. $this->outputFilename = sys_get_temp_dir() . '/' . uniqid() . '.zip';
  23. }
  24. /**
  25. * After test
  26. */
  27. protected function tearDown()
  28. {
  29. parent::tearDown();
  30. if ($this->outputFilename !== null && file_exists($this->outputFilename)) {
  31. unlink($this->outputFilename);
  32. }
  33. }
  34. /**
  35. * Test create, open and extract empty archive.
  36. */
  37. public function testEmptyArchive()
  38. {
  39. $zipFile = new ZipFile();
  40. $zipFile->saveAsFile($this->outputFilename);
  41. $zipFile->close();
  42. self::assertCorrectEmptyZip($this->outputFilename);
  43. $extractPath = sys_get_temp_dir() . '/extract-empty-dir';
  44. if (is_dir($extractPath)) {
  45. FilesUtil::removeDir($extractPath);
  46. }
  47. self::assertTrue(mkdir($extractPath, 0755, true));
  48. $zipFile->openFile($this->outputFilename);
  49. self::assertEquals(count($zipFile), 0);
  50. self::assertEquals($zipFile->count(), 0);
  51. $zipFile->extractTo($extractPath);
  52. $zipFile->close();
  53. self::assertTrue(FilesUtil::isEmptyDir($extractPath));
  54. FilesUtil::removeDir($extractPath);
  55. }
  56. /**
  57. * @expectedException \PhpZip\Exception\InvalidArgumentException
  58. * @expectedExceptionMessage can't exists
  59. */
  60. public function testCantExistsOpenFile()
  61. {
  62. $zipFile = new ZipFile();
  63. $zipFile->openFile(uniqid());
  64. }
  65. /**
  66. * @expectedException \PhpZip\Exception\ZipException
  67. * @expectedExceptionMessage can't open
  68. */
  69. public function testCantOpenFile()
  70. {
  71. self::assertNotFalse(file_put_contents($this->outputFilename, 'content'));
  72. self::assertTrue(chmod($this->outputFilename, 0222));
  73. $zipFile = new ZipFile();
  74. $zipFile->openFile($this->outputFilename);
  75. }
  76. /**
  77. * @expectedException \PhpZip\Exception\InvalidArgumentException
  78. * @expectedExceptionMessage Data not available
  79. */
  80. public function testOpenFromStringNull()
  81. {
  82. $zipFile = new ZipFile();
  83. $zipFile->openFromString(null);
  84. }
  85. /**
  86. * @expectedException \PhpZip\Exception\InvalidArgumentException
  87. * @expectedExceptionMessage Data not available
  88. */
  89. public function testOpenFromStringEmpty()
  90. {
  91. $zipFile = new ZipFile();
  92. $zipFile->openFromString("");
  93. }
  94. public function testOpenFromString()
  95. {
  96. $zipFile = new ZipFile();
  97. $zipFile->addFromString('file', 'content', ZipFile::METHOD_DEFLATED);
  98. $zipContents = $zipFile->outputAsString();
  99. $zipFile->close();
  100. $zipFile->openFromString($zipContents);
  101. self::assertTrue(isset($zipFile['file']));
  102. self::assertEquals($zipFile['file'], 'content');
  103. $zipFile->close();
  104. }
  105. public function testOpenFromStream()
  106. {
  107. $zipFile = new ZipFile();
  108. $zipFile->addFromString('file', 'content', ZipFile::METHOD_DEFLATED)
  109. ->saveAsFile($this->outputFilename);
  110. $zipFile->close();
  111. $handle = fopen($this->outputFilename, 'rb');
  112. $zipFile->openFromStream($handle);
  113. self::assertTrue(isset($zipFile['file']));
  114. self::assertEquals($zipFile['file'], 'content');
  115. $zipFile->close();
  116. }
  117. /**
  118. * @expectedException \PhpZip\Exception\InvalidArgumentException
  119. * @expectedExceptionMessage Invalid stream resource
  120. */
  121. public function testOpenFromInvalidStream()
  122. {
  123. $zipFile = new ZipFile();
  124. $zipFile->openFromStream("stream resource");
  125. }
  126. /**
  127. * @expectedException \PhpZip\Exception\InvalidArgumentException
  128. * @expectedExceptionMessage Resource cannot seekable stream.
  129. */
  130. public function testOpenFromStreamNoSeekable()
  131. {
  132. if (!$fp = @fopen("http://localhost", 'r')) {
  133. if (!$fp = @fopen("http://example.org", 'r')) {
  134. $this->markTestSkipped('not connected to localhost or remote host');
  135. return;
  136. }
  137. }
  138. $zipFile = new ZipFile();
  139. $zipFile->openFromStream($fp);
  140. }
  141. /**
  142. * No modified archive
  143. *
  144. * @see ZipOutputFile::create()
  145. */
  146. public function testNoModifiedArchive()
  147. {
  148. $zipFile = new ZipFile();
  149. $zipFile->addDir(__DIR__);
  150. $zipFile->saveAsFile($this->outputFilename);
  151. $zipFile->close();
  152. self::assertCorrectZipArchive($this->outputFilename);
  153. $zipFile->openFile($this->outputFilename);
  154. $zipFile->saveAsFile($this->outputFilename);
  155. $zipFile->close();
  156. self::assertCorrectZipArchive($this->outputFilename);
  157. }
  158. /**
  159. * Create archive and add files.
  160. *
  161. * @see ZipOutputFile::addFromString()
  162. * @see ZipOutputFile::addFromFile()
  163. * @see ZipOutputFile::addFromStream()
  164. * @see ZipFile::getEntryContent()
  165. */
  166. public function testCreateArchiveAndAddFiles()
  167. {
  168. $outputFromString = file_get_contents(__FILE__);
  169. $outputFromString2 = file_get_contents(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'README.md');
  170. $outputFromFile = file_get_contents(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'bootstrap.xml');
  171. $outputFromStream = file_get_contents(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'composer.json');
  172. $filenameFromString = basename(__FILE__);
  173. $filenameFromString2 = 'test_file.txt';
  174. $filenameFromFile = 'data/test file.txt';
  175. $filenameFromStream = 'data/ডিরেক্টরি/αρχείο.json';
  176. $emptyDirName = 'empty dir/пустой каталог/空目錄/ไดเรกทอรีที่ว่างเปล่า/';
  177. $emptyDirName2 = 'empty dir/пустой каталог/';
  178. $emptyDirName3 = 'empty dir/пустой каталог/ещё один пустой каталог/';
  179. $tempFile = tempnam(sys_get_temp_dir(), 'txt');
  180. file_put_contents($tempFile, $outputFromFile);
  181. $tempStream = tmpfile();
  182. fwrite($tempStream, $outputFromStream);
  183. $zipFile = new ZipFile;
  184. $zipFile->addFromString($filenameFromString, $outputFromString);
  185. $zipFile->addFile($tempFile, $filenameFromFile);
  186. $zipFile->addFromStream($tempStream, $filenameFromStream);
  187. $zipFile->addEmptyDir($emptyDirName);
  188. $zipFile[$filenameFromString2] = $outputFromString2;
  189. $zipFile[$emptyDirName2] = null;
  190. $zipFile[$emptyDirName3] = 'this content ignoring';
  191. $zipFile->saveAsFile($this->outputFilename);
  192. $zipFile->close();
  193. unlink($tempFile);
  194. self::assertCorrectZipArchive($this->outputFilename);
  195. $zipFile->openFile($this->outputFilename);
  196. self::assertEquals(count($zipFile), 7);
  197. self::assertEquals($zipFile[$filenameFromString], $outputFromString);
  198. self::assertEquals($zipFile[$filenameFromFile], $outputFromFile);
  199. self::assertEquals($zipFile[$filenameFromStream], $outputFromStream);
  200. self::assertEquals($zipFile[$filenameFromString2], $outputFromString2);
  201. self::assertTrue(isset($zipFile[$emptyDirName]));
  202. self::assertTrue(isset($zipFile[$emptyDirName2]));
  203. self::assertTrue(isset($zipFile[$emptyDirName3]));
  204. self::assertTrue($zipFile->isDirectory($emptyDirName));
  205. self::assertTrue($zipFile->isDirectory($emptyDirName2));
  206. self::assertTrue($zipFile->isDirectory($emptyDirName3));
  207. $listFiles = $zipFile->getListFiles();
  208. self::assertEquals($listFiles[0], $filenameFromString);
  209. self::assertEquals($listFiles[1], $filenameFromFile);
  210. self::assertEquals($listFiles[2], $filenameFromStream);
  211. self::assertEquals($listFiles[3], $emptyDirName);
  212. self::assertEquals($listFiles[4], $filenameFromString2);
  213. self::assertEquals($listFiles[5], $emptyDirName2);
  214. self::assertEquals($listFiles[6], $emptyDirName3);
  215. $zipFile->close();
  216. }
  217. /**
  218. * Test compression method from image file.
  219. */
  220. public function testCompressionMethodFromImageMimeType()
  221. {
  222. if (!function_exists('mime_content_type')) {
  223. $this->markTestSkipped('Function mime_content_type not exists');
  224. }
  225. $outputFilename = $this->outputFilename;
  226. $this->outputFilename .= '.gif';
  227. self::assertNotFalse(
  228. file_put_contents(
  229. $this->outputFilename,
  230. base64_decode('R0lGODlhAQABAJAAAP8AAAAAACH5BAUQAAAALAAAAAABAAEAAAICBAEAOw==')
  231. )
  232. );
  233. $basename = basename($this->outputFilename);
  234. $zipFile = new ZipFile();
  235. $zipFile->addFile($this->outputFilename, $basename);
  236. $zipFile->saveAsFile($outputFilename);
  237. unlink($this->outputFilename);
  238. $this->outputFilename = $outputFilename;
  239. $zipFile->openFile($this->outputFilename);
  240. $info = $zipFile->getEntryInfo($basename);
  241. self::assertEquals($info->getMethod(), 'No compression');
  242. $zipFile->close();
  243. }
  244. /**
  245. * Create archive and add directory recursively.
  246. */
  247. public function testAddDirRecursively()
  248. {
  249. $inputDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . "src";
  250. $zipFile = new ZipFile();
  251. $zipFile->addDir($inputDir);
  252. $zipFile->saveAsFile($this->outputFilename);
  253. $zipFile->close();
  254. self::assertCorrectZipArchive($this->outputFilename);
  255. }
  256. /**
  257. * Create archive and add directory not recursively.
  258. */
  259. public function testAddDirNotRecursively()
  260. {
  261. $inputDir = dirname(dirname(__DIR__));
  262. $recursive = false;
  263. $zipFile = new ZipFile();
  264. $zipFile->addDir($inputDir, $recursive);
  265. $zipFile->saveAsFile($this->outputFilename);
  266. $zipFile->close();
  267. self::assertCorrectZipArchive($this->outputFilename);
  268. }
  269. /**
  270. * Create archive and add directory and put files to path.
  271. */
  272. public function testAddDirAndMoveToPath()
  273. {
  274. $inputDir = __DIR__;
  275. $files = array_slice(scandir($inputDir), 2);
  276. $recursive = true;
  277. $zipFile = new ZipFile();
  278. $moveToPath = 'Library/tests';
  279. $zipFile->addDir($inputDir, $recursive, $moveToPath);
  280. $zipFile->saveAsFile($this->outputFilename);
  281. $zipFile->close();
  282. self::assertCorrectZipArchive($this->outputFilename);
  283. $zipFile->openFile($this->outputFilename);
  284. self::assertEquals(count($zipFile), count($files));
  285. foreach ($files as $file) {
  286. self::assertTrue(isset($zipFile[$moveToPath . '/' . $file]));
  287. self::assertEquals($zipFile[$moveToPath . '/' . $file], file_get_contents($inputDir . '/' . $file));
  288. }
  289. $zipFile->close();
  290. }
  291. /**
  292. * Create archive and add directory with ignore files list.
  293. */
  294. public function testAddDirAndIgnoreFiles()
  295. {
  296. $inputDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
  297. $recursive = false;
  298. $zipFile = new ZipFile();
  299. $ignoreFiles = ['tests/', '.git/', 'composer.lock', 'vendor/', ".idea/"];
  300. $moveToPath = 'PhpZip Library';
  301. $zipFile->addDir($inputDir, $recursive, $moveToPath, $ignoreFiles);
  302. $zipFile->saveAsFile($this->outputFilename);
  303. $zipFile->close();
  304. self::assertCorrectZipArchive($this->outputFilename);
  305. }
  306. /**
  307. * Create archive and add directory recursively with ignore files list.
  308. */
  309. public function testAddDirAndIgnoreFilesRecursively()
  310. {
  311. $inputDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
  312. $recursive = true;
  313. $zipFile = new ZipFile();
  314. $ignoreFiles = ['tests/', '.git/', 'composer.lock', 'vendor/', ".idea/copyright/"];
  315. $moveToPath = 'PhpZip Library';
  316. $zipFile->addDir($inputDir, $recursive, $moveToPath, $ignoreFiles);
  317. $zipFile->saveAsFile($this->outputFilename);
  318. $zipFile->close();
  319. self::assertCorrectZipArchive($this->outputFilename);
  320. }
  321. /**
  322. * Create archive and add files from glob pattern
  323. */
  324. public function testAddFilesFromGlob()
  325. {
  326. $inputDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
  327. $moveToPath = null;
  328. $recursive = false;
  329. $zipFile = new ZipFile();
  330. $zipFile->addFilesFromGlob($inputDir, '**.{php,xml}', $moveToPath, $recursive);
  331. $zipFile->saveAsFile($this->outputFilename);
  332. $zipFile->close();
  333. self::assertCorrectZipArchive($this->outputFilename);
  334. }
  335. /**
  336. * Create archive and add recursively files from glob pattern
  337. */
  338. public function testAddFilesFromGlobRecursive()
  339. {
  340. $inputDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
  341. $moveToPath = "PhpZip Library";
  342. $recursive = true;
  343. $zipFile = new ZipFile();
  344. $zipFile->addFilesFromGlob($inputDir, '**.{php,xml}', $moveToPath, $recursive);
  345. $zipFile->saveAsFile($this->outputFilename);
  346. $zipFile->close();
  347. self::assertCorrectZipArchive($this->outputFilename);
  348. }
  349. /**
  350. * Create archive and add files from regex pattern
  351. */
  352. public function testAddFilesFromRegex()
  353. {
  354. $inputDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
  355. $moveToPath = "Test";
  356. $recursive = false;
  357. $zipFile = new ZipFile();
  358. $zipFile->addFilesFromRegex($inputDir, '~\.(xml|php)$~i', $moveToPath, $recursive);
  359. $zipFile->saveAsFile($this->outputFilename);
  360. $zipFile->close();
  361. self::assertCorrectZipArchive($this->outputFilename);
  362. }
  363. /**
  364. * Create archive and add files recursively from regex pattern
  365. */
  366. public function testAddFilesFromRegexRecursive()
  367. {
  368. $inputDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
  369. $moveToPath = "Test";
  370. $recursive = true;
  371. $zipFile = new ZipFile();
  372. $zipFile->addFilesFromRegex($inputDir, '~\.(xml|php)$~i', $recursive, $moveToPath);
  373. $zipFile->saveAsFile($this->outputFilename);
  374. $zipFile->close();
  375. self::assertCorrectZipArchive($this->outputFilename);
  376. }
  377. /**
  378. * Rename zip entry name.
  379. */
  380. public function testRename()
  381. {
  382. $oldName = basename(__FILE__);
  383. $newName = 'tests/' . $oldName;
  384. $zipFile = new ZipFile();
  385. $zipFile->addDir(__DIR__);
  386. $zipFile->saveAsFile($this->outputFilename);
  387. $zipFile->close();
  388. self::assertCorrectZipArchive($this->outputFilename);
  389. $zipFile->openFile($this->outputFilename);
  390. $zipFile->rename($oldName, $newName);
  391. $zipFile->addFromString('file1.txt', 'content');
  392. $zipFile->rename('file1.txt', 'file2.txt');
  393. $zipFile->saveAsFile($this->outputFilename);
  394. $zipFile->close();
  395. self::assertCorrectZipArchive($this->outputFilename);
  396. $zipFile->openFile($this->outputFilename);
  397. self::assertFalse(isset($zipFile[$oldName]));
  398. self::assertTrue(isset($zipFile[$newName]));
  399. self::assertFalse(isset($zipFile['file1.txt']));
  400. self::assertTrue(isset($zipFile['file2.txt']));
  401. $zipFile->close();
  402. }
  403. /**
  404. * Delete entry from name.
  405. */
  406. public function testDeleteFromName()
  407. {
  408. $inputDir = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
  409. $deleteEntryName = 'composer.json';
  410. $zipFile = new ZipFile();
  411. $zipFile->addDir($inputDir, false);
  412. $zipFile->saveAsFile($this->outputFilename);
  413. $zipFile->close();
  414. self::assertCorrectZipArchive($this->outputFilename);
  415. $zipFile->openFile($this->outputFilename);
  416. $zipFile->deleteFromName($deleteEntryName);
  417. $zipFile->saveAsFile($this->outputFilename);
  418. $zipFile->close();
  419. self::assertCorrectZipArchive($this->outputFilename);
  420. $zipFile->openFile($this->outputFilename);
  421. self::assertFalse(isset($zipFile[$deleteEntryName]));
  422. $zipFile->close();
  423. }
  424. /**
  425. * Delete zip entries from glob pattern
  426. */
  427. public function testDeleteFromGlob()
  428. {
  429. $inputDir = dirname(dirname(__DIR__));
  430. $zipFile = new ZipFile();
  431. $zipFile->addFilesFromGlob($inputDir, '**.{php,xml,json}', '/', true);
  432. $zipFile->saveAsFile($this->outputFilename);
  433. $zipFile->close();
  434. self::assertCorrectZipArchive($this->outputFilename);
  435. $zipFile->openFile($this->outputFilename);
  436. $zipFile->deleteFromGlob('**.{xml,json}');
  437. $zipFile->saveAsFile($this->outputFilename);
  438. $zipFile->close();
  439. self::assertCorrectZipArchive($this->outputFilename);
  440. $zipFile->openFile($this->outputFilename);
  441. self::assertFalse(isset($zipFile['composer.json']));
  442. self::assertFalse(isset($zipFile['bootstrap.xml']));
  443. $zipFile->close();
  444. }
  445. /**
  446. * @expectedException \PhpZip\Exception\InvalidArgumentException
  447. * @expectedExceptionMessage Glob pattern is empty
  448. */
  449. public function testDeleteFromGlobFailNull(){
  450. $zipFile = new ZipFile();
  451. $zipFile->deleteFromGlob(null);
  452. }
  453. /**
  454. * @expectedException \PhpZip\Exception\InvalidArgumentException
  455. * @expectedExceptionMessage Glob pattern is empty
  456. */
  457. public function testDeleteFromGlobFailEmpty(){
  458. $zipFile = new ZipFile();
  459. $zipFile->deleteFromGlob('');
  460. }
  461. /**
  462. * Delete entries from regex pattern
  463. */
  464. public function testDeleteFromRegex()
  465. {
  466. $inputDir = dirname(dirname(__DIR__));
  467. $zipFile = new ZipFile();
  468. $zipFile->addFilesFromRegex($inputDir, '~\.(xml|php|json)$~i', 'Path', true);
  469. $zipFile->saveAsFile($this->outputFilename);
  470. $zipFile->close();
  471. self::assertCorrectZipArchive($this->outputFilename);
  472. $zipFile->openFile($this->outputFilename);
  473. $zipFile->deleteFromRegex('~\.(json)$~i');
  474. $zipFile->saveAsFile($this->outputFilename);
  475. $zipFile->close();
  476. self::assertCorrectZipArchive($this->outputFilename);
  477. $zipFile->openFile($this->outputFilename);
  478. self::assertFalse(isset($zipFile['Path/composer.json']));
  479. self::assertTrue(isset($zipFile['Path/bootstrap.xml']));
  480. $zipFile->close();
  481. }
  482. /**
  483. * @expectedException \PhpZip\Exception\InvalidArgumentException
  484. * @expectedExceptionMessage Regex pattern is empty.
  485. */
  486. public function testDeleteFromRegexFailNull(){
  487. $zipFile = new ZipFile();
  488. $zipFile->deleteFromRegex(null);
  489. }
  490. /**
  491. * @expectedException \PhpZip\Exception\InvalidArgumentException
  492. * @expectedExceptionMessage Regex pattern is empty.
  493. */
  494. public function testDeleteFromRegexFailEmpty(){
  495. $zipFile = new ZipFile();
  496. $zipFile->deleteFromRegex('');
  497. }
  498. /**
  499. * Delete all entries
  500. */
  501. public function testDeleteAll()
  502. {
  503. $zipFile = new ZipFile();
  504. $zipFile->addDir(__DIR__);
  505. $zipFile->saveAsFile($this->outputFilename);
  506. $zipFile->close();
  507. self::assertCorrectZipArchive($this->outputFilename);
  508. $zipFile->openFile($this->outputFilename);
  509. self::assertTrue($zipFile->count() > 0);
  510. $zipFile->deleteAll();
  511. $zipFile->saveAsFile($this->outputFilename);
  512. $zipFile->close();
  513. self::assertCorrectEmptyZip($this->outputFilename);
  514. $zipFile->openFile($this->outputFilename);
  515. self::assertEquals($zipFile->count(), 0);
  516. $zipFile->close();
  517. }
  518. /**
  519. * Test zip archive comment.
  520. */
  521. public function testArchiveComment()
  522. {
  523. $comment = "This zip file comment" . PHP_EOL
  524. . "Αυτό το σχόλιο αρχείο zip" . PHP_EOL
  525. . "Это комментарий zip архива" . PHP_EOL
  526. . "這個ZIP文件註釋" . PHP_EOL
  527. . "ეს zip ფაილის კომენტარი" . PHP_EOL
  528. . "このzipファイルにコメント" . PHP_EOL
  529. . "ความคิดเห็นนี้ไฟล์ซิป";
  530. $zipFile = new ZipFile();
  531. $zipFile->setArchiveComment($comment);
  532. $zipFile->addFile(__FILE__);
  533. $zipFile->saveAsFile($this->outputFilename);
  534. $zipFile->close();
  535. self::assertCorrectZipArchive($this->outputFilename);
  536. $zipFile->openFile($this->outputFilename);
  537. self::assertEquals($zipFile->getArchiveComment(), $comment);
  538. $zipFile->setArchiveComment(null); // remove archive comment
  539. $zipFile->saveAsFile($this->outputFilename);
  540. $zipFile->close();
  541. self::assertCorrectZipArchive($this->outputFilename);
  542. // check empty comment
  543. $zipFile->openFile($this->outputFilename);
  544. self::assertEquals($zipFile->getArchiveComment(), "");
  545. $zipFile->close();
  546. }
  547. /**
  548. * Test very long archive comment.
  549. *
  550. * @expectedException \PhpZip\Exception\InvalidArgumentException
  551. */
  552. public function testVeryLongArchiveComment()
  553. {
  554. $comment = "Very long comment" . PHP_EOL .
  555. "Очень длинный комментарий" . PHP_EOL;
  556. $comment = str_repeat($comment, ceil(0xffff / strlen($comment)) + strlen($comment) + 1);
  557. $zipFile = new ZipFile();
  558. $zipFile->setArchiveComment($comment);
  559. }
  560. /**
  561. * Test zip entry comment.
  562. */
  563. public function testEntryComment()
  564. {
  565. $entries = [
  566. '文件1.txt' => [
  567. 'data' => CryptoUtil::randomBytes(255),
  568. 'comment' => "這是註釋的條目。",
  569. ],
  570. 'file2.txt' => [
  571. 'data' => CryptoUtil::randomBytes(255),
  572. 'comment' => null
  573. ],
  574. 'file3.txt' => [
  575. 'data' => CryptoUtil::randomBytes(255),
  576. 'comment' => CryptoUtil::randomBytes(255),
  577. ],
  578. 'file4.txt' => [
  579. 'data' => CryptoUtil::randomBytes(255),
  580. 'comment' => "Комментарий файла"
  581. ],
  582. 'file5.txt' => [
  583. 'data' => CryptoUtil::randomBytes(255),
  584. 'comment' => "ไฟล์แสดงความคิดเห็น"
  585. ],
  586. 'file6 emoji 🙍🏼.txt' => [
  587. 'data' => CryptoUtil::randomBytes(255),
  588. 'comment' => "Emoji comment file - 😀 ⛈ ❤️ 🤴🏽"
  589. ],
  590. ];
  591. // create archive with entry comments
  592. $zipFile = new ZipFile();
  593. foreach ($entries as $entryName => $item) {
  594. $zipFile->addFromString($entryName, $item['data']);
  595. $zipFile->setEntryComment($entryName, $item['comment']);
  596. }
  597. $zipFile->saveAsFile($this->outputFilename);
  598. $zipFile->close();
  599. self::assertCorrectZipArchive($this->outputFilename);
  600. // check and modify comments
  601. $zipFile->openFile($this->outputFilename);
  602. foreach ($zipFile->getListFiles() as $entryName) {
  603. $entriesItem = $entries[$entryName];
  604. self::assertNotEmpty($entriesItem);
  605. self::assertEquals($zipFile[$entryName], $entriesItem['data']);
  606. self::assertEquals($zipFile->getEntryComment($entryName), (string)$entriesItem['comment']);
  607. }
  608. // modify comment
  609. $entries['file5.txt']['comment'] = mt_rand(1, 100000000);
  610. $zipFile->setEntryComment('file5.txt', $entries['file5.txt']['comment']);
  611. $zipFile->saveAsFile($this->outputFilename);
  612. $zipFile->close();
  613. self::assertCorrectZipArchive($this->outputFilename);
  614. // check modify comments
  615. $zipFile->openFile($this->outputFilename);
  616. foreach ($entries as $entryName => $entriesItem) {
  617. self::assertTrue(isset($zipFile[$entryName]));
  618. self::assertEquals($zipFile->getEntryComment($entryName), (string)$entriesItem['comment']);
  619. self::assertEquals($zipFile[$entryName], $entriesItem['data']);
  620. }
  621. $zipFile->close();
  622. }
  623. /**
  624. * Test zip entry very long comment.
  625. *
  626. * @expectedException \PhpZip\Exception\ZipException
  627. */
  628. public function testVeryLongEntryComment()
  629. {
  630. $comment = "Very long comment" . PHP_EOL .
  631. "Очень длинный комментарий" . PHP_EOL;
  632. $comment = str_repeat($comment, ceil(0xffff / strlen($comment)) + strlen($comment) + 1);
  633. $zipFile = new ZipFile();
  634. $zipFile->addFile(__FILE__, 'test');
  635. $zipFile->setEntryComment('test', $comment);
  636. }
  637. /**
  638. * Test all available support compression methods.
  639. */
  640. public function testCompressionMethod()
  641. {
  642. $entries = [
  643. '1' => [
  644. 'data' => CryptoUtil::randomBytes(255),
  645. 'method' => ZipFile::METHOD_STORED,
  646. 'expected' => 'No compression',
  647. ],
  648. '2' => [
  649. 'data' => CryptoUtil::randomBytes(255),
  650. 'method' => ZipFile::METHOD_DEFLATED,
  651. 'expected' => 'Deflate',
  652. ],
  653. ];
  654. if (extension_loaded("bz2")) {
  655. $entries['3'] = [
  656. 'data' => CryptoUtil::randomBytes(255),
  657. 'method' => ZipFile::METHOD_BZIP2,
  658. 'expected' => 'Bzip2',
  659. ];
  660. }
  661. $zipFile = new ZipFile();
  662. foreach ($entries as $entryName => $item) {
  663. $zipFile->addFromString($entryName, $item['data'], $item['method']);
  664. }
  665. $zipFile->saveAsFile($this->outputFilename);
  666. $zipFile->close();
  667. self::assertCorrectZipArchive($this->outputFilename);
  668. $zipFile->openFile($this->outputFilename);
  669. $zipFile->setCompressionLevel(ZipFile::LEVEL_BEST_COMPRESSION);
  670. $zipAllInfo = $zipFile->getAllInfo();
  671. foreach ($zipAllInfo as $entryName => $info) {
  672. self::assertEquals($zipFile[$entryName], $entries[$entryName]['data']);
  673. self::assertEquals($info->getMethod(), $entries[$entryName]['expected']);
  674. $entryInfo = $zipFile->getEntryInfo($entryName);
  675. self::assertEquals($entryInfo, $info);
  676. }
  677. $zipFile->close();
  678. }
  679. /**
  680. * Test extract all files.
  681. */
  682. public function testExtract()
  683. {
  684. $entries = [
  685. 'test1.txt' => CryptoUtil::randomBytes(255),
  686. 'test2.txt' => CryptoUtil::randomBytes(255),
  687. 'test/test 2/test3.txt' => CryptoUtil::randomBytes(255),
  688. 'test empty/dir' => null,
  689. ];
  690. $extractPath = sys_get_temp_dir() . '/zipExtract' . uniqid();
  691. if (!is_dir($extractPath)) {
  692. mkdir($extractPath, 0755, true);
  693. }
  694. $zipFile = new ZipFile();
  695. foreach ($entries as $entryName => $value) {
  696. if ($value === null) {
  697. $zipFile->addEmptyDir($entryName);
  698. } else {
  699. $zipFile->addFromString($entryName, $value);
  700. }
  701. }
  702. $zipFile->saveAsFile($this->outputFilename);
  703. $zipFile->close();
  704. $zipFile->openFile($this->outputFilename);
  705. $zipFile->extractTo($extractPath);
  706. foreach ($entries as $entryName => $value) {
  707. $fullExtractedFilename = $extractPath . DIRECTORY_SEPARATOR . $entryName;
  708. if ($value === null) {
  709. self::assertTrue(is_dir($fullExtractedFilename));
  710. self::assertTrue(FilesUtil::isEmptyDir($fullExtractedFilename));
  711. } else {
  712. self::assertTrue(is_file($fullExtractedFilename));
  713. $contents = file_get_contents($fullExtractedFilename);
  714. self::assertEquals($contents, $value);
  715. }
  716. }
  717. $zipFile->close();
  718. FilesUtil::removeDir($extractPath);
  719. }
  720. /**
  721. * Test extract some files
  722. */
  723. public function testExtractSomeFiles()
  724. {
  725. $entries = [
  726. 'test1.txt' => CryptoUtil::randomBytes(255),
  727. 'test2.txt' => CryptoUtil::randomBytes(255),
  728. 'test3.txt' => CryptoUtil::randomBytes(255),
  729. 'test4.txt' => CryptoUtil::randomBytes(255),
  730. 'test5.txt' => CryptoUtil::randomBytes(255),
  731. 'test/test/test.txt' => CryptoUtil::randomBytes(255),
  732. 'test/test/test 2.txt' => CryptoUtil::randomBytes(255),
  733. 'test empty/dir/' => null,
  734. 'test empty/dir2/' => null,
  735. ];
  736. $extractEntries = [
  737. 'test1.txt',
  738. 'test3.txt',
  739. 'test5.txt',
  740. 'test/test/test 2.txt',
  741. 'test empty/dir2/'
  742. ];
  743. $extractPath = sys_get_temp_dir() . '/zipExtractTest';
  744. if (is_dir($extractPath)) {
  745. FilesUtil::removeDir($extractPath);
  746. }
  747. self::assertTrue(mkdir($extractPath, 0755, true));
  748. $zipFile = new ZipFile();
  749. $zipFile->addAll($entries);
  750. $zipFile->saveAsFile($this->outputFilename);
  751. $zipFile->close();
  752. $zipFile->openFile($this->outputFilename);
  753. $zipFile->extractTo($extractPath, $extractEntries);
  754. foreach ($entries as $entryName => $value) {
  755. $fullExtractFilename = $extractPath . DIRECTORY_SEPARATOR . $entryName;
  756. if (in_array($entryName, $extractEntries)) {
  757. if ($value === null) {
  758. self::assertTrue(is_dir($fullExtractFilename));
  759. self::assertTrue(FilesUtil::isEmptyDir($fullExtractFilename));
  760. } else {
  761. self::assertTrue(is_file($fullExtractFilename));
  762. $contents = file_get_contents($fullExtractFilename);
  763. self::assertEquals($contents, $value);
  764. }
  765. } else {
  766. if ($value === null) {
  767. self::assertFalse(is_dir($fullExtractFilename));
  768. } else {
  769. self::assertFalse(is_file($fullExtractFilename));
  770. }
  771. }
  772. }
  773. self::assertFalse(is_file($extractPath . DIRECTORY_SEPARATOR . 'test/test/test.txt'));
  774. $zipFile->extractTo($extractPath, 'test/test/test.txt');
  775. self::assertTrue(is_file($extractPath . DIRECTORY_SEPARATOR . 'test/test/test.txt'));
  776. $zipFile->close();
  777. FilesUtil::removeDir($extractPath);
  778. }
  779. /**
  780. * @expectedException \PhpZip\Exception\ZipException
  781. * @expectedExceptionMessage not found
  782. */
  783. public function testExtractFail()
  784. {
  785. $zipFile = new ZipFile();
  786. $zipFile['file'] = 'content';
  787. $zipFile->saveAsFile($this->outputFilename);
  788. $zipFile->close();
  789. $zipFile->openFile($this->outputFilename);
  790. $zipFile->extractTo('path/to/path');
  791. }
  792. /**
  793. * @expectedException \PhpZip\Exception\ZipException
  794. * @expectedExceptionMessage Destination is not directory
  795. */
  796. public function testExtractFail2()
  797. {
  798. $zipFile = new ZipFile();
  799. $zipFile['file'] = 'content';
  800. $zipFile->saveAsFile($this->outputFilename);
  801. $zipFile->close();
  802. $zipFile->openFile($this->outputFilename);
  803. $zipFile->extractTo($this->outputFilename);
  804. }
  805. /**
  806. * @expectedException \PhpZip\Exception\ZipException
  807. * @expectedExceptionMessage Destination is not writable directory
  808. */
  809. public function testExtractFail3()
  810. {
  811. $zipFile = new ZipFile();
  812. $zipFile['file'] = 'content';
  813. $zipFile->saveAsFile($this->outputFilename);
  814. $zipFile->close();
  815. $extractPath = sys_get_temp_dir() . '/zipExtractTest';
  816. if (is_dir($extractPath)) {
  817. FilesUtil::removeDir($extractPath);
  818. }
  819. self::assertTrue(mkdir($extractPath, 0444, true));
  820. self::assertTrue(chmod($extractPath, 0444));
  821. $zipFile->openFile($this->outputFilename);
  822. $zipFile->extractTo($extractPath);
  823. }
  824. /**
  825. * Test archive password.
  826. */
  827. public function testSetPassword()
  828. {
  829. $password = base64_encode(CryptoUtil::randomBytes(100));
  830. $badPassword = "sdgt43r23wefe";
  831. // create encryption password with ZipCrypto
  832. $zipFile = new ZipFile();
  833. $zipFile->addDir(__DIR__);
  834. $zipFile->withNewPassword($password, ZipFile::ENCRYPTION_METHOD_TRADITIONAL);
  835. $zipFile->saveAsFile($this->outputFilename);
  836. $zipFile->close();
  837. self::assertCorrectZipArchive($this->outputFilename, $password);
  838. // check bad password for ZipCrypto
  839. $zipFile->openFile($this->outputFilename);
  840. $zipFile->withReadPassword($badPassword);
  841. foreach ($zipFile->getListFiles() as $entryName) {
  842. try {
  843. $zipFile[$entryName];
  844. self::fail("Expected Exception has not been raised.");
  845. } catch (ZipAuthenticationException $ae) {
  846. self::assertNotNull($ae);
  847. }
  848. }
  849. // check correct password for ZipCrypto
  850. $zipFile->withReadPassword($password);
  851. foreach ($zipFile->getAllInfo() as $info) {
  852. self::assertTrue($info->isEncrypted());
  853. self::assertContains('ZipCrypto', $info->getMethod());
  854. $decryptContent = $zipFile[$info->getPath()];
  855. self::assertNotEmpty($decryptContent);
  856. self::assertContains('<?php', $decryptContent);
  857. }
  858. // change encryption method to WinZip Aes and update file
  859. $zipFile->withNewPassword($password, ZipFile::ENCRYPTION_METHOD_WINZIP_AES);
  860. $zipFile->saveAsFile($this->outputFilename);
  861. $zipFile->close();
  862. self::assertCorrectZipArchive($this->outputFilename, $password);
  863. // check from WinZip AES encryption
  864. $zipFile->openFile($this->outputFilename);
  865. // set bad password WinZip AES
  866. $zipFile->withReadPassword($badPassword);
  867. foreach ($zipFile->getListFiles() as $entryName) {
  868. try {
  869. $zipFile[$entryName];
  870. self::fail("Expected Exception has not been raised.");
  871. } catch (ZipAuthenticationException $ae) {
  872. self::assertNotNull($ae);
  873. }
  874. }
  875. // set correct password WinZip AES
  876. $zipFile->withReadPassword($password);
  877. foreach ($zipFile->getAllInfo() as $info) {
  878. self::assertTrue($info->isEncrypted());
  879. self::assertContains('WinZip', $info->getMethod());
  880. $decryptContent = $zipFile[$info->getPath()];
  881. self::assertNotEmpty($decryptContent);
  882. self::assertContains('<?php', $decryptContent);
  883. }
  884. // clear password
  885. $zipFile->addFromString('file1', '');
  886. $zipFile->withoutPassword();
  887. $zipFile->addFromString('file2', '');
  888. $zipFile->saveAsFile($this->outputFilename);
  889. $zipFile->close();
  890. self::assertCorrectZipArchive($this->outputFilename);
  891. // check remove password
  892. $zipFile->openFile($this->outputFilename);
  893. foreach ($zipFile->getAllInfo() as $info) {
  894. self::assertFalse($info->isEncrypted());
  895. }
  896. $zipFile->close();
  897. }
  898. /**
  899. * @expectedException \PhpZip\Exception\InvalidArgumentException
  900. * @expectedExceptionMessage entryName is null
  901. */
  902. public function testAddFromArrayAccessNullName()
  903. {
  904. $zipFile = new ZipFile();
  905. $zipFile[null] = 'content';
  906. }
  907. /**
  908. * @expectedException \PhpZip\Exception\InvalidArgumentException
  909. * @expectedExceptionMessage entryName is empty
  910. */
  911. public function testAddFromArrayAccessEmptyName()
  912. {
  913. $zipFile = new ZipFile();
  914. $zipFile[''] = 'content';
  915. }
  916. /**
  917. * @expectedException \PhpZip\Exception\InvalidArgumentException
  918. * @expectedExceptionMessage Contents is null
  919. */
  920. public function testAddFromStringNullContents()
  921. {
  922. $zipFile = new ZipFile();
  923. $zipFile->addFromString('file', null);
  924. }
  925. /**
  926. * @expectedException \PhpZip\Exception\InvalidArgumentException
  927. * @expectedExceptionMessage Incorrect entry name
  928. */
  929. public function testAddFromStringNullEntryName()
  930. {
  931. $zipFile = new ZipFile();
  932. $zipFile->addFromString(null, 'contents');
  933. }
  934. /**
  935. * @expectedException \PhpZip\Exception\ZipUnsupportMethod
  936. * @expectedExceptionMessage Unsupported method
  937. */
  938. public function testAddFromStringUnsupportedMethod()
  939. {
  940. $zipFile = new ZipFile();
  941. $zipFile->addFromString('file', 'contents', ZipEntry::METHOD_WINZIP_AES);
  942. }
  943. /**
  944. * @expectedException \PhpZip\Exception\InvalidArgumentException
  945. * @expectedExceptionMessage Incorrect entry name
  946. */
  947. public function testAddFromStringEmptyEntryName()
  948. {
  949. $zipFile = new ZipFile();
  950. $zipFile->addFromString('', 'contents');
  951. }
  952. /**
  953. * Test compression method from add string.
  954. */
  955. public function testAddFromStringCompressionMethod()
  956. {
  957. $fileStored = sys_get_temp_dir() . '/zip-stored.txt';
  958. $fileDeflated = sys_get_temp_dir() . '/zip-deflated.txt';
  959. self::assertNotFalse(file_put_contents($fileStored, 'content'));
  960. self::assertNotFalse(file_put_contents($fileDeflated, str_repeat('content', 200)));
  961. $zipFile = new ZipFile();
  962. $zipFile->addFromString(basename($fileStored), file_get_contents($fileStored));
  963. $zipFile->addFromString(basename($fileDeflated), file_get_contents($fileDeflated));
  964. $zipFile->saveAsFile($this->outputFilename);
  965. $zipFile->close();
  966. unlink($fileStored);
  967. unlink($fileDeflated);
  968. $zipFile->openFile($this->outputFilename);
  969. $infoStored = $zipFile->getEntryInfo(basename($fileStored));
  970. $infoDeflated = $zipFile->getEntryInfo(basename($fileDeflated));
  971. self::assertEquals($infoStored->getMethod(), 'No compression');
  972. self::assertEquals($infoDeflated->getMethod(), 'Deflate');
  973. $zipFile->close();
  974. }
  975. /**
  976. * @expectedException \PhpZip\Exception\InvalidArgumentException
  977. * @expectedExceptionMessage stream is not resource
  978. */
  979. public function testAddFromStreamInvalidResource()
  980. {
  981. $zipFile = new ZipFile();
  982. $zipFile->addFromStream("invalid resource", "name");
  983. }
  984. /**
  985. * @expectedException \PhpZip\Exception\InvalidArgumentException
  986. * @expectedExceptionMessage Incorrect entry name
  987. */
  988. public function testAddFromStreamEmptyEntryName()
  989. {
  990. $handle = fopen(__FILE__, 'rb');
  991. $zipFile = new ZipFile();
  992. $zipFile->addFromStream($handle, "");
  993. }
  994. /**
  995. * @expectedException \PhpZip\Exception\ZipUnsupportMethod
  996. * @expectedExceptionMessage Unsupported method
  997. */
  998. public function testAddFromStreamUnsupportedMethod()
  999. {
  1000. $handle = fopen(__FILE__, 'rb');
  1001. $zipFile = new ZipFile();
  1002. $zipFile->addFromStream($handle, basename(__FILE__), ZipEntry::METHOD_WINZIP_AES);
  1003. }
  1004. /**
  1005. * Test compression method from add stream.
  1006. */
  1007. public function testAddFromStreamCompressionMethod()
  1008. {
  1009. $fileStored = sys_get_temp_dir() . '/zip-stored.txt';
  1010. $fileDeflated = sys_get_temp_dir() . '/zip-deflated.txt';
  1011. self::assertNotFalse(file_put_contents($fileStored, 'content'));
  1012. self::assertNotFalse(file_put_contents($fileDeflated, str_repeat('content', 200)));
  1013. $fpStored = fopen($fileStored, 'rb');
  1014. $fpDeflated = fopen($fileDeflated, 'rb');
  1015. $zipFile = new ZipFile();
  1016. $zipFile->addFromStream($fpStored, basename($fileStored));
  1017. $zipFile->addFromStream($fpDeflated, basename($fileDeflated));
  1018. $zipFile->saveAsFile($this->outputFilename);
  1019. $zipFile->close();
  1020. unlink($fileStored);
  1021. unlink($fileDeflated);
  1022. $zipFile->openFile($this->outputFilename);
  1023. $infoStored = $zipFile->getEntryInfo(basename($fileStored));
  1024. $infoDeflated = $zipFile->getEntryInfo(basename($fileDeflated));
  1025. self::assertEquals($infoStored->getMethod(), 'No compression');
  1026. self::assertEquals($infoDeflated->getMethod(), 'Deflate');
  1027. $zipFile->close();
  1028. }
  1029. /**
  1030. * @expectedException \PhpZip\Exception\InvalidArgumentException
  1031. * @expectedExceptionMessage Filename is null
  1032. */
  1033. public function testAddFileNullFileName()
  1034. {
  1035. $zipFile = new ZipFile();
  1036. $zipFile->addFile(null);
  1037. }
  1038. /**
  1039. * @expectedException \PhpZip\Exception\InvalidArgumentException
  1040. * @expectedExceptionMessage File is not exists
  1041. */
  1042. public function testAddFileCantExists()
  1043. {
  1044. $zipFile = new ZipFile();
  1045. $zipFile->addFile('path/to/file');
  1046. }
  1047. /**
  1048. * @expectedException \PhpZip\Exception\ZipUnsupportMethod
  1049. * @expectedExceptionMessage Unsupported method
  1050. */
  1051. public function testAddFileUnsupportedMethod()
  1052. {
  1053. $zipFile = new ZipFile();
  1054. $zipFile->addFile(__FILE__, null, ZipEntry::METHOD_WINZIP_AES);
  1055. }
  1056. /**
  1057. * @expectedException \PhpZip\Exception\InvalidArgumentException
  1058. * @expectedExceptionMessage can not open
  1059. */
  1060. public function testAddFileCantOpen()
  1061. {
  1062. self::assertNotFalse(file_put_contents($this->outputFilename, ''));
  1063. self::assertTrue(chmod($this->outputFilename, 0244));
  1064. $zipFile = new ZipFile();
  1065. $zipFile->addFile($this->outputFilename);
  1066. }
  1067. /**
  1068. * @expectedException \PhpZip\Exception\InvalidArgumentException
  1069. * @expectedExceptionMessage handle is not resource
  1070. */
  1071. public function testSaveAsStreamBadStream()
  1072. {
  1073. $zipFile = new ZipFile();
  1074. $zipFile->saveAsStream("bad stream");
  1075. }
  1076. /**
  1077. * @expectedException \PhpZip\Exception\InvalidArgumentException
  1078. * @expectedExceptionMessage can not open from write
  1079. */
  1080. public function testSaveAsFileNotWritable()
  1081. {
  1082. $this->outputFilename = sys_get_temp_dir() . '/zipExtractTest';
  1083. if (is_dir($this->outputFilename)) {
  1084. FilesUtil::removeDir($this->outputFilename);
  1085. }
  1086. self::assertTrue(mkdir($this->outputFilename, 0444, true));
  1087. self::assertTrue(chmod($this->outputFilename, 0444));
  1088. $this->outputFilename .= '/' . uniqid() . '.zip';
  1089. $zipFile = new ZipFile();
  1090. $zipFile->saveAsFile($this->outputFilename);
  1091. }
  1092. /**
  1093. * Test `ZipFile` implemented \ArrayAccess, \Countable and |iterator.
  1094. */
  1095. public function testZipFileArrayAccessAndCountableAndIterator()
  1096. {
  1097. $files = [];
  1098. $numFiles = mt_rand(20, 100);
  1099. for ($i = 0; $i < $numFiles; $i++) {
  1100. $files['file' . $i . '.txt'] = CryptoUtil::randomBytes(255);
  1101. }
  1102. $methods = [ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED];
  1103. if (extension_loaded("bz2")) {
  1104. $methods[] = ZipFile::METHOD_BZIP2;
  1105. }
  1106. $zipFile = new ZipFile();
  1107. $zipFile->setCompressionLevel(ZipFile::LEVEL_BEST_SPEED);
  1108. foreach ($files as $entryName => $content) {
  1109. $zipFile->addFromString($entryName, $content, $methods[array_rand($methods)]);
  1110. }
  1111. $zipFile->saveAsFile($this->outputFilename);
  1112. $zipFile->close();
  1113. self::assertCorrectZipArchive($this->outputFilename);
  1114. $zipFile->openFile($this->outputFilename);
  1115. // Test \Countable
  1116. self::assertEquals($zipFile->count(), $numFiles);
  1117. self::assertEquals(count($zipFile), $numFiles);
  1118. // Test \ArrayAccess
  1119. reset($files);
  1120. foreach ($zipFile as $entryName => $content) {
  1121. self::assertEquals($entryName, key($files));
  1122. self::assertEquals($content, current($files));
  1123. next($files);
  1124. }
  1125. // Test \Iterator
  1126. reset($files);
  1127. $iterator = new \ArrayIterator($zipFile);
  1128. $iterator->rewind();
  1129. while ($iterator->valid()) {
  1130. $key = $iterator->key();
  1131. $value = $iterator->current();
  1132. self::assertEquals($key, key($files));
  1133. self::assertEquals($value, current($files));
  1134. next($files);
  1135. $iterator->next();
  1136. }
  1137. $zipFile->close();
  1138. $zipFile = new ZipFile();
  1139. $zipFile['file1.txt'] = 'content 1';
  1140. $zipFile['dir/file2.txt'] = 'content 1';
  1141. $zipFile['dir/empty dir/'] = null;
  1142. $zipFile->saveAsFile($this->outputFilename);
  1143. $zipFile->close();
  1144. self::assertCorrectZipArchive($this->outputFilename);
  1145. $zipFile->openFile($this->outputFilename);
  1146. self::assertTrue(isset($zipFile['file1.txt']));
  1147. self::assertTrue(isset($zipFile['dir/file2.txt']));
  1148. self::assertTrue(isset($zipFile['dir/empty dir/']));
  1149. self::assertFalse(isset($zipFile['dir/empty dir/2/']));
  1150. $zipFile['dir/empty dir/2/'] = null;
  1151. unset($zipFile['dir/file2.txt'], $zipFile['dir/empty dir/']);
  1152. $zipFile->saveAsFile($this->outputFilename);
  1153. $zipFile->close();
  1154. self::assertCorrectZipArchive($this->outputFilename);
  1155. $zipFile->openFile($this->outputFilename);
  1156. self::assertTrue(isset($zipFile['file1.txt']));
  1157. self::assertFalse(isset($zipFile['dir/file2.txt']));
  1158. self::assertFalse(isset($zipFile['dir/empty dir/']));
  1159. self::assertTrue(isset($zipFile['dir/empty dir/2/']));
  1160. $zipFile->close();
  1161. }
  1162. /**
  1163. * @expectedException \PhpZip\Exception\InvalidArgumentException
  1164. * @expectedExceptionMessage DirName empty
  1165. */
  1166. public function testAddEmptyDirNullName()
  1167. {
  1168. $zipFile = new ZipFile();
  1169. $zipFile->addEmptyDir(null);
  1170. }
  1171. /**
  1172. * @expectedException \PhpZip\Exception\InvalidArgumentException
  1173. * @expectedExceptionMessage DirName empty
  1174. */
  1175. public function testAddEmptyDirEmptyName()
  1176. {
  1177. $zipFile = new ZipFile();
  1178. $zipFile->addEmptyDir("");
  1179. }
  1180. /**
  1181. * Test zip alignment.
  1182. */
  1183. public function testZipAlign()
  1184. {
  1185. $zipFile = new ZipFile();
  1186. for ($i = 0; $i < 100; $i++) {
  1187. $zipFile->addFromString(
  1188. 'entry' . $i . '.txt',
  1189. CryptoUtil::randomBytes(mt_rand(100, 4096)),
  1190. ZipFile::METHOD_STORED
  1191. );
  1192. }
  1193. $zipFile->saveAsFile($this->outputFilename);
  1194. $zipFile->close();
  1195. self::assertCorrectZipArchive($this->outputFilename);
  1196. $result = self::doZipAlignVerify($this->outputFilename);
  1197. if ($result === null) return; // zip align not installed
  1198. // check not zip align
  1199. self::assertFalse($result);
  1200. $zipFile->openFile($this->outputFilename);
  1201. $zipFile->setZipAlign(4);
  1202. $zipFile->saveAsFile($this->outputFilename);
  1203. $zipFile->close();
  1204. self::assertCorrectZipArchive($this->outputFilename);
  1205. $result = self::doZipAlignVerify($this->outputFilename, true);
  1206. self::assertNotNull($result);
  1207. // check zip align
  1208. self::assertTrue($result);
  1209. $zipFile = new ZipFile();
  1210. for ($i = 0; $i < 100; $i++) {
  1211. $zipFile->addFromString(
  1212. 'entry' . $i . '.txt',
  1213. CryptoUtil::randomBytes(mt_rand(100, 4096)),
  1214. ZipFile::METHOD_STORED
  1215. );
  1216. }
  1217. $zipFile->setZipAlign(4);
  1218. $zipFile->saveAsFile($this->outputFilename);
  1219. $zipFile->close();
  1220. self::assertCorrectZipArchive($this->outputFilename);
  1221. $result = self::doZipAlignVerify($this->outputFilename);
  1222. // check not zip align
  1223. self::assertTrue($result);
  1224. }
  1225. /**
  1226. * Test support ZIP64 ext (slow test - normal).
  1227. * Create > 65535 files in archive and open and extract to /dev/null.
  1228. */
  1229. public function testCreateAndOpenZip64Ext()
  1230. {
  1231. $countFiles = 0xffff + 1;
  1232. $zipFile = new ZipFile();
  1233. for ($i = 0; $i < $countFiles; $i++) {
  1234. $zipFile[$i . '.txt'] = $i;
  1235. }
  1236. $zipFile->saveAsFile($this->outputFilename);
  1237. $zipFile->close();
  1238. self::assertCorrectZipArchive($this->outputFilename);
  1239. $zipFile->openFile($this->outputFilename);
  1240. self::assertEquals($zipFile->count(), $countFiles);
  1241. foreach ($zipFile as $entry => $content) {
  1242. }
  1243. $zipFile->close();
  1244. }
  1245. }