1
0
mirror of https://github.com/Ne-Lexa/php-zip.git synced 2025-08-03 14:07:23 +02:00

PHP-doc updated (@throws added everywhere) and minor refactoring done.

This commit is contained in:
wapplay
2018-10-09 10:06:04 +03:00
parent 59773d62a8
commit f9e6a73587
38 changed files with 942 additions and 684 deletions

View File

@@ -41,7 +41,8 @@
"suggest": { "suggest": {
"ext-openssl": "Needed to support encrypt zip entries or use ext-mcrypt", "ext-openssl": "Needed to support encrypt zip entries or use ext-mcrypt",
"ext-mcrypt": "Needed to support encrypt zip entries or use ext-openssl", "ext-mcrypt": "Needed to support encrypt zip entries or use ext-openssl",
"ext-bz2": "Needed to support BZIP2 compression" "ext-bz2": "Needed to support BZIP2 compression",
"ext-fileinfo": "Needed to get mime-type file"
}, },
"minimum-stability": "stable" "minimum-stability": "stable"
} }

View File

@@ -176,6 +176,7 @@ class TraditionalPkwareEncryptionEngine implements ZipEncryptionEngine
* *
* @param string $data * @param string $data
* @return string * @return string
* @throws ZipCryptoException
*/ */
public function encrypt($data) public function encrypt($data)
{ {
@@ -202,7 +203,7 @@ class TraditionalPkwareEncryptionEngine implements ZipEncryptionEngine
*/ */
private function encryptData($content) private function encryptData($content)
{ {
if (null === $content) { if ($content === null) {
throw new ZipCryptoException('content is null'); throw new ZipCryptoException('content is null');
} }
$buff = ''; $buff = '';

View File

@@ -5,6 +5,7 @@ namespace PhpZip\Crypto;
use PhpZip\Exception\RuntimeException; use PhpZip\Exception\RuntimeException;
use PhpZip\Exception\ZipAuthenticationException; use PhpZip\Exception\ZipAuthenticationException;
use PhpZip\Exception\ZipCryptoException; use PhpZip\Exception\ZipCryptoException;
use PhpZip\Exception\ZipException;
use PhpZip\Extra\Fields\WinZipAesEntryExtraField; use PhpZip\Extra\Fields\WinZipAesEntryExtraField;
use PhpZip\Model\ZipEntry; use PhpZip\Model\ZipEntry;
use PhpZip\Util\CryptoUtil; use PhpZip\Util\CryptoUtil;
@@ -49,6 +50,7 @@ class WinZipAesEngine implements ZipEncryptionEngine
* @return string * @return string
* @throws ZipAuthenticationException * @throws ZipAuthenticationException
* @throws ZipCryptoException * @throws ZipCryptoException
* @throws \PhpZip\Exception\ZipException
*/ */
public function decrypt($content) public function decrypt($content)
{ {
@@ -129,26 +131,26 @@ class WinZipAesEngine implements ZipEncryptionEngine
" (authenticated WinZip AES entry content has been tampered with)"); " (authenticated WinZip AES entry content has been tampered with)");
} }
return self::aesCtrSegmentIntegerCounter(false, $content, $key, $iv); return self::aesCtrSegmentIntegerCounter($content, $key, $iv, false);
} }
/** /**
* Decryption or encryption AES-CTR with Segment Integer Count (SIC). * Decryption or encryption AES-CTR with Segment Integer Count (SIC).
* *
* @param bool $encrypted If true encryption else decryption
* @param string $str Data * @param string $str Data
* @param string $key Key * @param string $key Key
* @param string $iv IV * @param string $iv IV
* @param bool $encrypted If true encryption else decryption
* @return string * @return string
*/ */
private static function aesCtrSegmentIntegerCounter($encrypted = true, $str, $key, $iv) private static function aesCtrSegmentIntegerCounter($str, $key, $iv, $encrypted = true)
{ {
$numOfBlocks = ceil(strlen($str) / 16); $numOfBlocks = ceil(strlen($str) / 16);
$ctrStr = ''; $ctrStr = '';
for ($i = 0; $i < $numOfBlocks; ++$i) { for ($i = 0; $i < $numOfBlocks; ++$i) {
for ($j = 0; $j < 16; ++$j) { for ($j = 0; $j < 16; ++$j) {
$n = ord($iv[$j]); $n = ord($iv[$j]);
if (0x100 === ++$n) { if (++$n === 0x100) {
// overflow, set this one to 0, increment next // overflow, set this one to 0, increment next
$iv[$j] = chr(0); $iv[$j] = chr(0);
} else { } else {
@@ -172,7 +174,6 @@ class WinZipAesEngine implements ZipEncryptionEngine
* @param string $key Aes key * @param string $key Aes key
* @param string $iv Aes IV * @param string $iv Aes IV
* @return string Encrypted data * @return string Encrypted data
* @throws RuntimeException
*/ */
private static function encryptCtr($data, $key, $iv) private static function encryptCtr($data, $key, $iv)
{ {
@@ -180,6 +181,7 @@ class WinZipAesEngine implements ZipEncryptionEngine
$numBits = strlen($key) * 8; $numBits = strlen($key) * 8;
return openssl_encrypt($data, 'AES-' . $numBits . '-CTR', $key, OPENSSL_RAW_DATA, $iv); return openssl_encrypt($data, 'AES-' . $numBits . '-CTR', $key, OPENSSL_RAW_DATA, $iv);
} elseif (extension_loaded("mcrypt")) { } elseif (extension_loaded("mcrypt")) {
/** @noinspection PhpDeprecationInspection */
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, "ctr", $iv); return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, "ctr", $iv);
} else { } else {
throw new RuntimeException('Extension openssl or mcrypt not loaded'); throw new RuntimeException('Extension openssl or mcrypt not loaded');
@@ -193,7 +195,6 @@ class WinZipAesEngine implements ZipEncryptionEngine
* @param string $key Aes key * @param string $key Aes key
* @param string $iv Aes IV * @param string $iv Aes IV
* @return string Raw data * @return string Raw data
* @throws RuntimeException
*/ */
private static function decryptCtr($data, $key, $iv) private static function decryptCtr($data, $key, $iv)
{ {
@@ -201,6 +202,7 @@ class WinZipAesEngine implements ZipEncryptionEngine
$numBits = strlen($key) * 8; $numBits = strlen($key) * 8;
return openssl_decrypt($data, 'AES-' . $numBits . '-CTR', $key, OPENSSL_RAW_DATA, $iv); return openssl_decrypt($data, 'AES-' . $numBits . '-CTR', $key, OPENSSL_RAW_DATA, $iv);
} elseif (extension_loaded("mcrypt")) { } elseif (extension_loaded("mcrypt")) {
/** @noinspection PhpDeprecationInspection */
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, "ctr", $iv); return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, "ctr", $iv);
} else { } else {
throw new RuntimeException('Extension openssl or mcrypt not loaded'); throw new RuntimeException('Extension openssl or mcrypt not loaded');
@@ -212,12 +214,15 @@ class WinZipAesEngine implements ZipEncryptionEngine
* *
* @param string $content * @param string $content
* @return string * @return string
* @throws \PhpZip\Exception\ZipException
*/ */
public function encrypt($content) public function encrypt($content)
{ {
// Init key strength. // Init key strength.
$password = $this->entry->getPassword(); $password = $this->entry->getPassword();
assert($password !== null); if ($password === null){
throw new ZipException('No password was set for the entry "'.$this->entry->getName().'"');
}
// WinZip 99-character limit // WinZip 99-character limit
// @see https://sourceforge.net/p/p7zip/discussion/383044/thread/c859a2f0/ // @see https://sourceforge.net/p/p7zip/discussion/383044/thread/c859a2f0/
@@ -226,8 +231,6 @@ class WinZipAesEngine implements ZipEncryptionEngine
$keyStrengthBits = WinZipAesEntryExtraField::getKeyStrangeFromEncryptionMethod($this->entry->getEncryptionMethod()); $keyStrengthBits = WinZipAesEntryExtraField::getKeyStrangeFromEncryptionMethod($this->entry->getEncryptionMethod());
$keyStrengthBytes = $keyStrengthBits / 8; $keyStrengthBytes = $keyStrengthBits / 8;
assert(self::AES_BLOCK_SIZE_BITS <= $keyStrengthBits);
$salt = CryptoUtil::randomBytes($keyStrengthBytes / 2); $salt = CryptoUtil::randomBytes($keyStrengthBytes / 2);
$keyParam = hash_pbkdf2("sha1", $password, $salt, self::ITERATION_COUNT, (2 * $keyStrengthBits + self::PWD_VERIFIER_BITS) / 8, true); $keyParam = hash_pbkdf2("sha1", $password, $salt, self::ITERATION_COUNT, (2 * $keyStrengthBits + self::PWD_VERIFIER_BITS) / 8, true);
@@ -239,7 +242,7 @@ class WinZipAesEngine implements ZipEncryptionEngine
$key = substr($keyParam, 0, $keyStrengthBytes); $key = substr($keyParam, 0, $keyStrengthBytes);
$content = self::aesCtrSegmentIntegerCounter(true, $content, $key, $iv); $content = self::aesCtrSegmentIntegerCounter($content, $key, $iv, true);
$mac = hash_hmac('sha1', $content, $sha1HMacParam, true); $mac = hash_hmac('sha1', $content, $sha1HMacParam, true);

View File

@@ -37,8 +37,14 @@ class Crc32Exception extends ZipException
*/ */
public function __construct($name, $expected, $actual) public function __construct($name, $expected, $actual)
{ {
parent::__construct($name . " (expected CRC32 value 0x" . parent::__construct(
dechex($expected) . ", but is actually 0x" . dechex($actual) . ")"); sprintf(
"%s (expected CRC32 value 0x%x, but is actually 0x%x)",
$name,
$expected,
$actual
)
);
assert($expected != $actual); assert($expected != $actual);
$this->expectedCrc = $expected; $this->expectedCrc = $expected;
$this->actualCrc = $actual; $this->actualCrc = $actual;

View File

@@ -4,10 +4,11 @@ namespace PhpZip\Exception;
/** /**
* Runtime exception. * Runtime exception.
* Exception thrown if an error which can only be found on runtime occurs.
* *
* @author Ne-Lexa alexey@nelexa.ru * @author Ne-Lexa alexey@nelexa.ru
* @license MIT * @license MIT
*/ */
class RuntimeException extends ZipException class RuntimeException extends \RuntimeException
{ {
} }

View File

@@ -0,0 +1,38 @@
<?php
namespace PhpZip\Exception;
/**
* Thrown if entry not found.
*
* @author Ne-Lexa alexey@nelexa.ru
* @license MIT
*/
class ZipEntryNotFoundException extends ZipException
{
/**
* @var string
*/
private $entryName;
/**
* ZipEntryNotFoundException constructor.
* @param string $entryName
*/
public function __construct($entryName)
{
parent::__construct(sprintf(
"Zip Entry \"%s\" was not found in the archive.",
$entryName
));
$this->entryName = $entryName;
}
/**
* @return string
*/
public function getEntryName()
{
return $this->entryName;
}
}

View File

@@ -7,8 +7,8 @@ namespace PhpZip\Exception;
* *
* @author Ne-Lexa alexey@nelexa.ru * @author Ne-Lexa alexey@nelexa.ru
* @license MIT * @license MIT
* @see \Exception * @deprecated Rename class exception, using ZipEntryNotFoundException
*/ */
class ZipNotFoundEntry extends ZipException class ZipNotFoundEntry extends ZipEntryNotFoundException
{ {
} }

View File

@@ -7,8 +7,8 @@ namespace PhpZip\Exception;
* *
* @author Ne-Lexa alexey@nelexa.ru * @author Ne-Lexa alexey@nelexa.ru
* @license MIT * @license MIT
* @see \Exception * @deprecated Rename exception class, using ZipUnsupportMethodException
*/ */
class ZipUnsupportMethod extends ZipException class ZipUnsupportMethod extends ZipUnsupportMethodException
{ {
} }

View File

@@ -0,0 +1,7 @@
<?php
namespace PhpZip\Exception;
class ZipUnsupportMethodException extends RuntimeException
{
}

View File

@@ -129,6 +129,7 @@ class ExtraFieldsCollection implements \Countable, \ArrayAccess, \Iterator
* </p> * </p>
* @return mixed Can return all value types. * @return mixed Can return all value types.
* @since 5.0.0 * @since 5.0.0
* @throws ZipException
*/ */
public function offsetGet($offset) public function offsetGet($offset)
{ {
@@ -145,13 +146,15 @@ class ExtraFieldsCollection implements \Countable, \ArrayAccess, \Iterator
* The value to set. * The value to set.
* </p> * </p>
* @return void * @return void
* @throws InvalidArgumentException * @throws ZipException
* @since 5.0.0 * @since 5.0.0
*/ */
public function offsetSet($offset, $value) public function offsetSet($offset, $value)
{ {
if ($value instanceof ExtraField) { if ($value instanceof ExtraField) {
assert($offset == $value::getHeaderId()); if ($offset !== $value::getHeaderId()){
throw new InvalidArgumentException("Value header id !== array access key");
}
$this->add($value); $this->add($value);
} else { } else {
throw new InvalidArgumentException('value is not instanceof ' . ExtraField::class); throw new InvalidArgumentException('value is not instanceof ' . ExtraField::class);
@@ -166,6 +169,7 @@ class ExtraFieldsCollection implements \Countable, \ArrayAccess, \Iterator
* </p> * </p>
* @return void * @return void
* @since 5.0.0 * @since 5.0.0
* @throws ZipException
*/ */
public function offsetUnset($offset) public function offsetUnset($offset)
{ {

View File

@@ -38,7 +38,7 @@ class ExtraFieldsFactory
public static function createExtraFieldCollections($extra, ZipEntry $entry = null) public static function createExtraFieldCollections($extra, ZipEntry $entry = null)
{ {
$extraFieldsCollection = new ExtraFieldsCollection(); $extraFieldsCollection = new ExtraFieldsCollection();
if (null !== $extra) { if ($extra !== null) {
$extraLength = strlen($extra); $extraLength = strlen($extra);
if ($extraLength > 0xffff) { if ($extraLength > 0xffff) {
throw new ZipException("Extra Fields too large: " . $extraLength); throw new ZipException("Extra Fields too large: " . $extraLength);
@@ -63,6 +63,11 @@ class ExtraFieldsFactory
return $extraFieldsCollection; return $extraFieldsCollection;
} }
/**
* @param ExtraFieldsCollection $extraFieldsCollection
* @return string
* @throws ZipException
*/
public static function createSerializedData(ExtraFieldsCollection $extraFieldsCollection) public static function createSerializedData(ExtraFieldsCollection $extraFieldsCollection)
{ {
$extraData = ''; $extraData = '';
@@ -102,7 +107,7 @@ class ExtraFieldsFactory
if (isset(self::getRegistry()[$headerId])) { if (isset(self::getRegistry()[$headerId])) {
$extraClassName = self::getRegistry()[$headerId]; $extraClassName = self::getRegistry()[$headerId];
$extraField = new $extraClassName; $extraField = new $extraClassName;
if ($extraField::getHeaderId() !== $headerId) { if ($headerId !== $extraField::getHeaderId()) {
throw new ZipException('Runtime error support headerId ' . $headerId); throw new ZipException('Runtime error support headerId ' . $headerId);
} }
} else { } else {
@@ -118,7 +123,7 @@ class ExtraFieldsFactory
*/ */
protected static function getRegistry() protected static function getRegistry()
{ {
if (null === self::$registry) { if (self::$registry === null) {
self::$registry[WinZipAesEntryExtraField::getHeaderId()] = WinZipAesEntryExtraField::class; self::$registry[WinZipAesEntryExtraField::getHeaderId()] = WinZipAesEntryExtraField::class;
self::$registry[NtfsExtraField::getHeaderId()] = NtfsExtraField::class; self::$registry[NtfsExtraField::getHeaderId()] = NtfsExtraField::class;
self::$registry[Zip64ExtraField::getHeaderId()] = Zip64ExtraField::class; self::$registry[Zip64ExtraField::getHeaderId()] = Zip64ExtraField::class;

View File

@@ -61,7 +61,6 @@ class ApkAlignmentExtraField implements ExtraField
/** /**
* Initializes this Extra Field by deserializing a Data Block. * Initializes this Extra Field by deserializing a Data Block.
* @param string $data * @param string $data
* @throws InvalidArgumentException
*/ */
public function deserialize($data) public function deserialize($data)
{ {

View File

@@ -44,7 +44,7 @@ class JarMarkerExtraField implements ExtraField
*/ */
public function deserialize($data) public function deserialize($data)
{ {
if (0 !== strlen($data)) { if (strlen($data) !== 0) {
throw new ZipException("JarMarker doesn't expect any data"); throw new ZipException("JarMarker doesn't expect any data");
} }
} }

View File

@@ -55,7 +55,7 @@ class NtfsExtraField implements ExtraField
public function deserialize($data) public function deserialize($data)
{ {
$unpack = unpack('vtag/vsizeAttr', substr($data, 0, 4)); $unpack = unpack('vtag/vsizeAttr', substr($data, 0, 4));
if (24 === $unpack['sizeAttr']) { if ($unpack['sizeAttr'] === 24) {
$tagData = substr($data, 4, $unpack['sizeAttr']); $tagData = substr($data, 4, $unpack['sizeAttr']);
$this->mtime = PackUtil::unpackLongLE(substr($tagData, 0, 8)) / 10000000 - 11644473600; $this->mtime = PackUtil::unpackLongLE(substr($tagData, 0, 8)) / 10000000 - 11644473600;
$this->atime = PackUtil::unpackLongLE(substr($tagData, 8, 8)) / 10000000 - 11644473600; $this->atime = PackUtil::unpackLongLE(substr($tagData, 8, 8)) / 10000000 - 11644473600;
@@ -70,7 +70,7 @@ class NtfsExtraField implements ExtraField
public function serialize() public function serialize()
{ {
$serialize = ''; $serialize = '';
if (null !== $this->mtime && null !== $this->atime && null !== $this->ctime) { if ($this->mtime !== null && $this->atime !== null && $this->ctime !== null) {
$mtimeLong = ($this->mtime + 11644473600) * 10000000; $mtimeLong = ($this->mtime + 11644473600) * 10000000;
$atimeLong = ($this->atime + 11644473600) * 10000000; $atimeLong = ($this->atime + 11644473600) * 10000000;
$ctimeLong = ($this->ctime + 11644473600) * 10000000; $ctimeLong = ($this->ctime + 11644473600) * 10000000;

View File

@@ -119,6 +119,7 @@ class WinZipAesEntryExtraField implements ExtraField
/** /**
* @return bool|int * @return bool|int
* @throws ZipException
*/ */
public function getKeyStrength() public function getKeyStrength()
{ {
@@ -153,6 +154,7 @@ class WinZipAesEntryExtraField implements ExtraField
* Internal encryption method. * Internal encryption method.
* *
* @return int * @return int
* @throws ZipException
*/ */
public function getEncryptionMethod() public function getEncryptionMethod()
{ {

View File

@@ -29,7 +29,7 @@ class Zip64ExtraField implements ExtraField
*/ */
public function __construct(ZipEntry $entry = null) public function __construct(ZipEntry $entry = null)
{ {
if (null !== $entry) { if ($entry !== null) {
$this->setEntry($entry); $this->setEntry($entry);
} }
} }
@@ -57,11 +57,10 @@ class Zip64ExtraField implements ExtraField
/** /**
* Serializes a Data Block. * Serializes a Data Block.
* @return string * @return string
* @throws RuntimeException
*/ */
public function serialize() public function serialize()
{ {
if (null === $this->entry) { if ($this->entry === null) {
throw new RuntimeException("entry is null"); throw new RuntimeException("entry is null");
} }
$data = ''; $data = '';
@@ -86,11 +85,11 @@ class Zip64ExtraField implements ExtraField
/** /**
* Initializes this Extra Field by deserializing a Data Block. * Initializes this Extra Field by deserializing a Data Block.
* @param string $data * @param string $data
* @throws RuntimeException * @throws \PhpZip\Exception\ZipException
*/ */
public function deserialize($data) public function deserialize($data)
{ {
if (null === $this->entry) { if ($this->entry === null) {
throw new RuntimeException("entry is null"); throw new RuntimeException("entry is null");
} }
$off = 0; $off = 0;

View File

@@ -109,6 +109,7 @@ abstract class ZipAbstractEntry implements ZipEntry
/** /**
* @param ZipEntry $entry * @param ZipEntry $entry
* @throws ZipException
*/ */
public function setEntry(ZipEntry $entry) public function setEntry(ZipEntry $entry)
{ {
@@ -212,7 +213,7 @@ abstract class ZipAbstractEntry implements ZipEntry
*/ */
protected function isInit($mask) protected function isInit($mask)
{ {
return 0 !== ($this->init & $mask); return ($this->init & $mask) !== 0;
} }
/** /**
@@ -274,7 +275,6 @@ abstract class ZipAbstractEntry implements ZipEntry
* *
* @param int $compressedSize The Compressed Size. * @param int $compressedSize The Compressed Size.
* @return ZipEntry * @return ZipEntry
* @throws ZipException
*/ */
public function setCompressedSize($compressedSize) public function setCompressedSize($compressedSize)
{ {
@@ -297,7 +297,6 @@ abstract class ZipAbstractEntry implements ZipEntry
* *
* @param int $size The (Uncompressed) Size. * @param int $size The (Uncompressed) Size.
* @return ZipEntry * @return ZipEntry
* @throws ZipException
*/ */
public function setSize($size) public function setSize($size)
{ {
@@ -318,7 +317,6 @@ abstract class ZipAbstractEntry implements ZipEntry
/** /**
* @param int $offset * @param int $offset
* @return ZipEntry * @return ZipEntry
* @throws ZipException
*/ */
public function setOffset($offset) public function setOffset($offset)
{ {
@@ -382,7 +380,7 @@ abstract class ZipAbstractEntry implements ZipEntry
*/ */
public function getGeneralPurposeBitFlag($mask) public function getGeneralPurposeBitFlag($mask)
{ {
return 0 !== ($this->general & $mask); return ($this->general & $mask) !== 0;
} }
/** /**
@@ -390,6 +388,7 @@ abstract class ZipAbstractEntry implements ZipEntry
* encryption artifacts. * encryption artifacts.
* *
* @return ZipEntry * @return ZipEntry
* @throws ZipException
*/ */
public function disableEncryption() public function disableEncryption()
{ {
@@ -401,7 +400,7 @@ abstract class ZipAbstractEntry implements ZipEntry
*/ */
$field = $this->extraFieldsCollection[$headerId]; $field = $this->extraFieldsCollection[$headerId];
if (self::METHOD_WINZIP_AES === $this->getMethod()) { if (self::METHOD_WINZIP_AES === $this->getMethod()) {
$this->setMethod(null === $field ? self::UNKNOWN : $field->getMethod()); $this->setMethod($field === null ? self::UNKNOWN : $field->getMethod());
} }
unset($this->extraFieldsCollection[$headerId]); unset($this->extraFieldsCollection[$headerId]);
} }
@@ -444,7 +443,7 @@ abstract class ZipAbstractEntry implements ZipEntry
*/ */
public function setMethod($method) public function setMethod($method)
{ {
if (self::UNKNOWN === $method) { if ($method === self::UNKNOWN) {
$this->method = $method; $this->method = $method;
$this->setInit(self::BIT_METHOD, false); $this->setInit(self::BIT_METHOD, false);
return $this; return $this;
@@ -510,6 +509,7 @@ abstract class ZipAbstractEntry implements ZipEntry
* *
* @param int $unixTimestamp * @param int $unixTimestamp
* @return ZipEntry * @return ZipEntry
* @throws ZipException
*/ */
public function setTime($unixTimestamp) public function setTime($unixTimestamp)
{ {
@@ -541,7 +541,6 @@ abstract class ZipAbstractEntry implements ZipEntry
* *
* @param int $externalAttributes the external file attributes. * @param int $externalAttributes the external file attributes.
* @return ZipEntry * @return ZipEntry
* @throws ZipException
*/ */
public function setExternalAttributes($externalAttributes) public function setExternalAttributes($externalAttributes)
{ {
@@ -619,7 +618,7 @@ abstract class ZipAbstractEntry implements ZipEntry
*/ */
public function setComment($comment) public function setComment($comment)
{ {
if (null !== $comment) { if ($comment !== null) {
$commentLength = strlen($comment); $commentLength = strlen($comment);
if (0x0000 > $commentLength || $commentLength > 0xffff) { if (0x0000 > $commentLength || $commentLength > 0xffff) {
throw new ZipException("Comment too long"); throw new ZipException("Comment too long");
@@ -635,7 +634,7 @@ abstract class ZipAbstractEntry implements ZipEntry
*/ */
public function isDataDescriptorRequired() public function isDataDescriptorRequired()
{ {
return self::UNKNOWN == ($this->getCrc() | $this->getCompressedSize() | $this->getSize()); return ($this->getCrc() | $this->getCompressedSize() | $this->getSize()) == self::UNKNOWN;
} }
/** /**
@@ -653,7 +652,6 @@ abstract class ZipAbstractEntry implements ZipEntry
* *
* @param int $crc * @param int $crc
* @return ZipEntry * @return ZipEntry
* @throws ZipException
*/ */
public function setCrc($crc) public function setCrc($crc)
{ {
@@ -676,11 +674,12 @@ abstract class ZipAbstractEntry implements ZipEntry
* @param string $password * @param string $password
* @param null|int $encryptionMethod * @param null|int $encryptionMethod
* @return ZipEntry * @return ZipEntry
* @throws ZipException
*/ */
public function setPassword($password, $encryptionMethod = null) public function setPassword($password, $encryptionMethod = null)
{ {
$this->password = $password; $this->password = $password;
if (null !== $encryptionMethod) { if ($encryptionMethod !== null) {
$this->setEncryptionMethod($encryptionMethod); $this->setEncryptionMethod($encryptionMethod);
} }
if (!empty($this->password)) { if (!empty($this->password)) {
@@ -715,10 +714,10 @@ abstract class ZipAbstractEntry implements ZipEntry
{ {
if (null !== $encryptionMethod) { if (null !== $encryptionMethod) {
if ( if (
ZipFileInterface::ENCRYPTION_METHOD_TRADITIONAL !== $encryptionMethod $encryptionMethod !== ZipFileInterface::ENCRYPTION_METHOD_TRADITIONAL
&& ZipFileInterface::ENCRYPTION_METHOD_WINZIP_AES_128 !== $encryptionMethod && $encryptionMethod !== ZipFileInterface::ENCRYPTION_METHOD_WINZIP_AES_128
&& ZipFileInterface::ENCRYPTION_METHOD_WINZIP_AES_192 !== $encryptionMethod && $encryptionMethod !== ZipFileInterface::ENCRYPTION_METHOD_WINZIP_AES_192
&& ZipFileInterface::ENCRYPTION_METHOD_WINZIP_AES_256 !== $encryptionMethod && $encryptionMethod !== ZipFileInterface::ENCRYPTION_METHOD_WINZIP_AES_256
) { ) {
throw new ZipException('Invalid encryption method'); throw new ZipException('Invalid encryption method');
} }
@@ -738,7 +737,6 @@ abstract class ZipAbstractEntry implements ZipEntry
/** /**
* @param int $compressionLevel * @param int $compressionLevel
* @return ZipEntry * @return ZipEntry
* @throws InvalidArgumentException
*/ */
public function setCompressionLevel($compressionLevel = ZipFileInterface::LEVEL_DEFAULT_COMPRESSION) public function setCompressionLevel($compressionLevel = ZipFileInterface::LEVEL_DEFAULT_COMPRESSION)
{ {

View File

@@ -20,6 +20,8 @@ class ZipChangesEntry extends ZipAbstractEntry
/** /**
* ZipChangesEntry constructor. * ZipChangesEntry constructor.
* @param ZipSourceEntry $entry * @param ZipSourceEntry $entry
* @throws ZipException
* @throws \PhpZip\Exception\InvalidArgumentException
*/ */
public function __construct(ZipSourceEntry $entry) public function __construct(ZipSourceEntry $entry)
{ {
@@ -46,7 +48,6 @@ class ZipChangesEntry extends ZipAbstractEntry
* Returns an string content of the given entry. * Returns an string content of the given entry.
* *
* @return null|string * @return null|string
* @throws ZipException
*/ */
public function getEntryContent() public function getEntryContent()
{ {

View File

@@ -3,7 +3,6 @@
namespace PhpZip\Model\Entry; namespace PhpZip\Model\Entry;
use PhpZip\Exception\InvalidArgumentException; use PhpZip\Exception\InvalidArgumentException;
use PhpZip\Exception\ZipException;
use PhpZip\ZipFileInterface; use PhpZip\ZipFileInterface;
/** /**
@@ -27,7 +26,6 @@ class ZipNewEntry extends ZipAbstractEntry
/** /**
* ZipNewEntry constructor. * ZipNewEntry constructor.
* @param string|resource|null $content * @param string|resource|null $content
* @throws InvalidArgumentException
*/ */
public function __construct($content = null) public function __construct($content = null)
{ {
@@ -42,12 +40,12 @@ class ZipNewEntry extends ZipAbstractEntry
* Returns an string content of the given entry. * Returns an string content of the given entry.
* *
* @return null|string * @return null|string
* @throws ZipException
*/ */
public function getEntryContent() public function getEntryContent()
{ {
if (is_resource($this->content)) { if (is_resource($this->content)) {
return stream_get_contents($this->content, -1, 0); rewind($this->content);
return stream_get_contents($this->content);
} }
return $this->content; return $this->content;
} }
@@ -81,7 +79,7 @@ class ZipNewEntry extends ZipAbstractEntry
public function __destruct() public function __destruct()
{ {
if (!$this->clone && null !== $this->content && is_resource($this->content)) { if (!$this->clone && $this->content !== null && is_resource($this->content)) {
fclose($this->content); fclose($this->content);
$this->content = null; $this->content = null;
} }

View File

@@ -61,7 +61,8 @@ class ZipSourceEntry extends ZipAbstractEntry
*/ */
public function getEntryContent() public function getEntryContent()
{ {
if (null === $this->entryContent) { if ($this->entryContent === null) {
// In order not to unpack again, we cache the content in memory or on disk
$content = $this->inputStream->readEntryContent($this); $content = $this->inputStream->readEntryContent($this);
if ($this->getSize() < self::MAX_SIZE_CACHED_CONTENT_IN_MEMORY) { if ($this->getSize() < self::MAX_SIZE_CACHED_CONTENT_IN_MEMORY) {
$this->entryContent = $content; $this->entryContent = $content;
@@ -89,7 +90,7 @@ class ZipSourceEntry extends ZipAbstractEntry
public function __destruct() public function __destruct()
{ {
if (!$this->clone && null !== $this->entryContent && is_resource($this->entryContent)) { if (!$this->clone && $this->entryContent !== null && is_resource($this->entryContent)) {
fclose($this->entryContent); fclose($this->entryContent);
} }
} }

View File

@@ -145,7 +145,7 @@ class ZipEntryMatcher implements \Countable
$entry = $this->zipModel->getEntry($entry); $entry = $this->zipModel->getEntry($entry);
if (!$entry->isDirectory()) { if (!$entry->isDirectory()) {
$entry = $this->zipModel->getEntryForChanges($entry); $entry = $this->zipModel->getEntryForChanges($entry);
$entry->clearEncryption(); $entry->disableEncryption();
} }
}); });
} }

View File

@@ -186,6 +186,7 @@ class ZipInfo
* ZipInfo constructor. * ZipInfo constructor.
* *
* @param ZipEntry $entry * @param ZipEntry $entry
* @throws \PhpZip\Exception\ZipException
*/ */
public function __construct(ZipEntry $entry) public function __construct(ZipEntry $entry)
{ {
@@ -323,6 +324,7 @@ class ZipInfo
/** /**
* @param ZipEntry $entry * @param ZipEntry $entry
* @return int * @return int
* @throws \PhpZip\Exception\ZipException
*/ */
private static function getMethodId(ZipEntry $entry) private static function getMethodId(ZipEntry $entry)
{ {
@@ -344,6 +346,7 @@ class ZipInfo
/** /**
* @param ZipEntry $entry * @param ZipEntry $entry
* @return string * @return string
* @throws \PhpZip\Exception\ZipException
*/ */
private static function getEntryMethodName(ZipEntry $entry) private static function getEntryMethodName(ZipEntry $entry)
{ {

View File

@@ -3,8 +3,8 @@
namespace PhpZip\Model; namespace PhpZip\Model;
use PhpZip\Exception\InvalidArgumentException; use PhpZip\Exception\InvalidArgumentException;
use PhpZip\Exception\ZipEntryNotFoundException;
use PhpZip\Exception\ZipException; use PhpZip\Exception\ZipException;
use PhpZip\Exception\ZipNotFoundEntry;
use PhpZip\Model\Entry\ZipChangesEntry; use PhpZip\Model\Entry\ZipChangesEntry;
use PhpZip\Model\Entry\ZipSourceEntry; use PhpZip\Model\Entry\ZipSourceEntry;
use PhpZip\ZipFileInterface; use PhpZip\ZipFileInterface;
@@ -74,11 +74,10 @@ class ZipModel implements \Countable
/** /**
* @param string $comment * @param string $comment
* @throws InvalidArgumentException
*/ */
public function setArchiveComment($comment) public function setArchiveComment($comment)
{ {
if (null !== $comment && strlen($comment) !== 0) { if ($comment !== null && strlen($comment) !== 0) {
$comment = (string)$comment; $comment = (string)$comment;
$length = strlen($comment); $length = strlen($comment);
if (0x0000 > $length || $length > 0xffff) { if (0x0000 > $length || $length > 0xffff) {
@@ -97,6 +96,7 @@ class ZipModel implements \Countable
* Specify a password for extracting files. * Specify a password for extracting files.
* *
* @param null|string $password * @param null|string $password
* @throws ZipException
*/ */
public function setReadPassword($password) public function setReadPassword($password)
{ {
@@ -110,12 +110,13 @@ class ZipModel implements \Countable
/** /**
* @param string $entryName * @param string $entryName
* @param string $password * @param string $password
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
* @throws ZipException
*/ */
public function setReadPasswordEntry($entryName, $password) public function setReadPasswordEntry($entryName, $password)
{ {
if (!isset($this->inputEntries[$entryName])) { if (!isset($this->inputEntries[$entryName])) {
throw new ZipNotFoundEntry('Not found entry ' . $entryName); throw new ZipEntryNotFoundException($entryName);
} }
if ($this->inputEntries[$entryName]->isEncrypted()) { if ($this->inputEntries[$entryName]->isEncrypted()) {
$this->inputEntries[$entryName]->setPassword($password); $this->inputEntries[$entryName]->setPassword($password);
@@ -181,8 +182,7 @@ class ZipModel implements \Countable
/** /**
* @param string|ZipEntry $old * @param string|ZipEntry $old
* @param string|ZipEntry $new * @param string|ZipEntry $new
* @throws InvalidArgumentException * @throws ZipException
* @throws ZipNotFoundEntry
*/ */
public function renameEntry($old, $new) public function renameEntry($old, $new)
{ {
@@ -202,6 +202,8 @@ class ZipModel implements \Countable
/** /**
* @param string|ZipEntry $entry * @param string|ZipEntry $entry
* @return ZipChangesEntry|ZipEntry * @return ZipChangesEntry|ZipEntry
* @throws ZipException
* @throws ZipEntryNotFoundException
*/ */
public function getEntryForChanges($entry) public function getEntryForChanges($entry)
{ {
@@ -216,7 +218,7 @@ class ZipModel implements \Countable
/** /**
* @param string|ZipEntry $entryName * @param string|ZipEntry $entryName
* @return ZipEntry * @return ZipEntry
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
*/ */
public function getEntry($entryName) public function getEntry($entryName)
{ {
@@ -224,7 +226,7 @@ class ZipModel implements \Countable
if (isset($this->outEntries[$entryName])) { if (isset($this->outEntries[$entryName])) {
return $this->outEntries[$entryName]; return $this->outEntries[$entryName];
} }
throw new ZipNotFoundEntry('Zip entry "' . $entryName . '" not found'); throw new ZipEntryNotFoundException($entryName);
} }
/** /**
@@ -327,7 +329,6 @@ class ZipModel implements \Countable
/** /**
* @param int $encryptionMethod * @param int $encryptionMethod
* @throws ZipException
*/ */
public function setEncryptionMethod($encryptionMethod = ZipFileInterface::ENCRYPTION_METHOD_WINZIP_AES_256) public function setEncryptionMethod($encryptionMethod = ZipFileInterface::ENCRYPTION_METHOD_WINZIP_AES_256)
{ {

View File

@@ -9,7 +9,7 @@ use PhpZip\Exception\InvalidArgumentException;
use PhpZip\Exception\RuntimeException; use PhpZip\Exception\RuntimeException;
use PhpZip\Exception\ZipCryptoException; use PhpZip\Exception\ZipCryptoException;
use PhpZip\Exception\ZipException; use PhpZip\Exception\ZipException;
use PhpZip\Exception\ZipUnsupportMethod; use PhpZip\Exception\ZipUnsupportMethodException;
use PhpZip\Extra\ExtraFieldsCollection; use PhpZip\Extra\ExtraFieldsCollection;
use PhpZip\Extra\ExtraFieldsFactory; use PhpZip\Extra\ExtraFieldsFactory;
use PhpZip\Extra\Fields\ApkAlignmentExtraField; use PhpZip\Extra\Fields\ApkAlignmentExtraField;
@@ -56,7 +56,6 @@ class ZipInputStream implements ZipInputStreamInterface
/** /**
* ZipInputStream constructor. * ZipInputStream constructor.
* @param resource $in * @param resource $in
* @throws RuntimeException
*/ */
public function __construct($in) public function __construct($in)
{ {
@@ -69,6 +68,7 @@ class ZipInputStream implements ZipInputStreamInterface
/** /**
* @return ZipModel * @return ZipModel
* @throws ZipException
*/ */
public function readZip() public function readZip()
{ {
@@ -165,7 +165,7 @@ class ZipInputStream implements ZipInputStreamInterface
$offset = $endOfCentralDirRecordPos - $data['cdSize']; $offset = $endOfCentralDirRecordPos - $data['cdSize'];
fseek($this->in, $offset, SEEK_SET); fseek($this->in, $offset, SEEK_SET);
$offset -= $data['cdPos']; $offset -= $data['cdPos'];
if (0 !== $offset) { if ($offset !== 0) {
$this->mapper = new OffsetPositionMapper($offset); $this->mapper = new OffsetPositionMapper($offset);
} }
$entryCount = $data['cdEntries']; $entryCount = $data['cdEntries'];
@@ -262,14 +262,13 @@ class ZipInputStream implements ZipInputStreamInterface
$entries[$entry->getName()] = $entry; $entries[$entry->getName()] = $entry;
} }
if (0 !== $numEntries % 0x10000) { if (($numEntries % 0x10000) !== 0) {
throw new ZipException("Expected " . abs($numEntries) . throw new ZipException("Expected " . abs($numEntries) .
($numEntries > 0 ? " more" : " less") . ($numEntries > 0 ? " more" : " less") .
" entries in the Central Directory!"); " entries in the Central Directory!");
} }
if ($this->preamble + $this->postamble >= fstat($this->in)['size']) { if ($this->preamble + $this->postamble >= fstat($this->in)['size']) {
assert(0 === $numEntries);
$this->checkZipFileSignature(); $this->checkZipFileSignature();
} }
@@ -278,13 +277,13 @@ class ZipInputStream implements ZipInputStreamInterface
/** /**
* @return ZipEntry * @return ZipEntry
* @throws InvalidArgumentException * @throws ZipException
*/ */
public function readEntry() public function readEntry()
{ {
// central file header signature 4 bytes (0x02014b50) // central file header signature 4 bytes (0x02014b50)
$fileHeaderSig = unpack('V', fread($this->in, 4))[1]; $fileHeaderSig = unpack('V', fread($this->in, 4))[1];
if (ZipOutputStreamInterface::CENTRAL_FILE_HEADER_SIG !== $fileHeaderSig) { if ($fileHeaderSig !== ZipOutputStreamInterface::CENTRAL_FILE_HEADER_SIG) {
throw new InvalidArgumentException("Corrupt zip file. Can not read zip entry."); throw new InvalidArgumentException("Corrupt zip file. Can not read zip entry.");
} }
@@ -329,10 +328,10 @@ class ZipInputStream implements ZipInputStreamInterface
$entry->setSize($data['rawSize']); $entry->setSize($data['rawSize']);
$entry->setExternalAttributes($data['rawExternalAttributes']); $entry->setExternalAttributes($data['rawExternalAttributes']);
$entry->setOffset($data['lfhOff']); // must be unmapped! $entry->setOffset($data['lfhOff']); // must be unmapped!
if (0 < $data['extraLength']) { if ($data['extraLength'] > 0) {
$entry->setExtra(fread($this->in, $data['extraLength'])); $entry->setExtra(fread($this->in, $data['extraLength']));
} }
if (0 < $data['commentLength']) { if ($data['commentLength'] > 0) {
$entry->setComment(fread($this->in, $data['commentLength'])); $entry->setComment(fread($this->in, $data['commentLength']));
} }
return $entry; return $entry;
@@ -352,19 +351,20 @@ class ZipInputStream implements ZipInputStreamInterface
throw new InvalidArgumentException('entry must be ' . ZipSourceEntry::class); throw new InvalidArgumentException('entry must be ' . ZipSourceEntry::class);
} }
$isEncrypted = $entry->isEncrypted(); $isEncrypted = $entry->isEncrypted();
if ($isEncrypted && null === $entry->getPassword()) { if ($isEncrypted && $entry->getPassword() === null) {
throw new ZipException("Can not password from entry " . $entry->getName()); throw new ZipException("Can not password from entry " . $entry->getName());
} }
$pos = $entry->getOffset(); $pos = $entry->getOffset();
assert(ZipEntry::UNKNOWN !== $pos); $pos = PHP_INT_SIZE === 4
$pos = PHP_INT_SIZE === 4 ? sprintf('%u', $pos) : $pos; ? sprintf('%u', $pos) // PHP 32-Bit
: $pos; // PHP 64-Bit
$startPos = $pos = $this->mapper->map($pos); $startPos = $pos = $this->mapper->map($pos);
fseek($this->in, $startPos); fseek($this->in, $startPos);
// local file header signature 4 bytes (0x04034b50) // local file header signature 4 bytes (0x04034b50)
if (ZipEntry::LOCAL_FILE_HEADER_SIG !== unpack('V', fread($this->in, 4))[1]) { if (unpack('V', fread($this->in, 4))[1] !== ZipEntry::LOCAL_FILE_HEADER_SIG) {
throw new ZipException($entry->getName() . " (expected Local File Header)"); throw new ZipException($entry->getName() . " (expected Local File Header)");
} }
fseek($this->in, $pos + ZipEntry::LOCAL_FILE_HEADER_FILE_NAME_LENGTH_POS); fseek($this->in, $pos + ZipEntry::LOCAL_FILE_HEADER_FILE_NAME_LENGTH_POS);
@@ -390,7 +390,7 @@ class ZipInputStream implements ZipInputStreamInterface
$skipCheckCrc = false; $skipCheckCrc = false;
if ($isEncrypted) { if ($isEncrypted) {
if (ZipEntry::METHOD_WINZIP_AES === $method) { if ($method === ZipEntry::METHOD_WINZIP_AES) {
// Strong Encryption Specification - WinZip AES // Strong Encryption Specification - WinZip AES
$winZipAesEngine = new WinZipAesEngine($entry); $winZipAesEngine = new WinZipAesEngine($entry);
$content = $winZipAesEngine->decrypt($content); $content = $winZipAesEngine->decrypt($content);
@@ -418,7 +418,7 @@ class ZipInputStream implements ZipInputStreamInterface
// but older apps might not. // but older apps might not.
fseek($this->in, $pos + $compressedSize); fseek($this->in, $pos + $compressedSize);
$localCrc = unpack('V', fread($this->in, 4))[1]; $localCrc = unpack('V', fread($this->in, 4))[1];
if (ZipEntry::DATA_DESCRIPTOR_SIG === $localCrc) { if ($localCrc === ZipEntry::DATA_DESCRIPTOR_SIG) {
$localCrc = unpack('V', fread($this->in, 4))[1]; $localCrc = unpack('V', fread($this->in, 4))[1];
} }
} else { } else {
@@ -449,7 +449,7 @@ class ZipInputStream implements ZipInputStreamInterface
$content = bzdecompress($content); $content = bzdecompress($content);
break; break;
default: default:
throw new ZipUnsupportMethod($entry->getName() . throw new ZipUnsupportMethodException($entry->getName() .
" (compression method " . $method . " is not supported)"); " (compression method " . $method . " is not supported)");
} }
if (!$skipCheckCrc) { if (!$skipCheckCrc) {
@@ -480,6 +480,7 @@ class ZipInputStream implements ZipInputStreamInterface
* *
* @param ZipEntry $entry * @param ZipEntry $entry
* @param ZipOutputStreamInterface $out * @param ZipOutputStreamInterface $out
* @throws ZipException
*/ */
public function copyEntry(ZipEntry $entry, ZipOutputStreamInterface $out) public function copyEntry(ZipEntry $entry, ZipOutputStreamInterface $out)
{ {
@@ -551,8 +552,7 @@ class ZipInputStream implements ZipInputStreamInterface
// skip source extraLength from input stream // skip source extraLength from input stream
fseek($this->in, $sourceExtraLength, SEEK_CUR); fseek($this->in, $sourceExtraLength, SEEK_CUR);
} else { } else {
$copyInToOutLength += ZipEntry::LOCAL_FILE_HEADER_MIN_LEN + $sourceExtraLength + $nameLength; $copyInToOutLength += ZipEntry::LOCAL_FILE_HEADER_MIN_LEN + $sourceExtraLength + $nameLength;;
;
} }
if ($entry->getGeneralPurposeBitFlag(ZipEntry::GPBF_DATA_DESCRIPTOR)) { if ($entry->getGeneralPurposeBitFlag(ZipEntry::GPBF_DATA_DESCRIPTOR)) {
// crc-32 4 bytes // crc-32 4 bytes
@@ -595,7 +595,7 @@ class ZipInputStream implements ZipInputStreamInterface
public function close() public function close()
{ {
if ($this->in != null) { if ($this->in !== null) {
fclose($this->in); fclose($this->in);
$this->in = null; $this->in = null;
} }

View File

@@ -22,8 +22,7 @@ use PhpZip\Util\StringUtil;
use PhpZip\ZipFileInterface; use PhpZip\ZipFileInterface;
/** /**
* Write * Write zip file
* ip file
* *
* @author Ne-Lexa alexey@nelexa.ru * @author Ne-Lexa alexey@nelexa.ru
* @license MIT * @license MIT
@@ -43,7 +42,6 @@ class ZipOutputStream implements ZipOutputStreamInterface
* ZipOutputStream constructor. * ZipOutputStream constructor.
* @param resource $out * @param resource $out
* @param ZipModel $zipModel * @param ZipModel $zipModel
* @throws InvalidArgumentException
*/ */
public function __construct($out, ZipModel $zipModel) public function __construct($out, ZipModel $zipModel)
{ {
@@ -54,6 +52,9 @@ class ZipOutputStream implements ZipOutputStreamInterface
$this->zipModel = $zipModel; $this->zipModel = $zipModel;
} }
/**
* @throws ZipException
*/
public function writeZip() public function writeZip()
{ {
$entries = $this->zipModel->getEntries(); $entries = $this->zipModel->getEntries();
@@ -123,7 +124,7 @@ class ZipOutputStream implements ZipOutputStreamInterface
} }
$size = $nameLength + $extraLength; $size = $nameLength + $extraLength;
if (0xffff < $size) { if ($size > 0xffff) {
throw new ZipException( throw new ZipException(
$entry->getName() . " (the total size of " . $size . $entry->getName() . " (the total size of " . $size .
" bytes for the name, extra fields and comment " . " bytes for the name, extra fields and comment " .
@@ -168,7 +169,7 @@ class ZipOutputStream implements ZipOutputStreamInterface
if ($entry instanceof ZipChangesEntry && !$entry->isChangedContent()) { if ($entry instanceof ZipChangesEntry && !$entry->isChangedContent()) {
$entry->getSourceEntry()->getInputStream()->copyEntryData($entry->getSourceEntry(), $this); $entry->getSourceEntry()->getInputStream()->copyEntryData($entry->getSourceEntry(), $this);
} elseif (null !== $entryContent) { } elseif ($entryContent !== null) {
fwrite($this->out, $entryContent); fwrite($this->out, $entryContent);
} }
@@ -186,7 +187,7 @@ class ZipOutputStream implements ZipOutputStreamInterface
} else { } else {
fwrite($this->out, pack('VV', $entry->getCompressedSize(), $entry->getSize())); fwrite($this->out, pack('VV', $entry->getCompressedSize(), $entry->getSize()));
} }
} elseif ($entry->getCompressedSize() != $compressedSize) { } elseif ($compressedSize != $entry->getCompressedSize()) {
throw new ZipException( throw new ZipException(
$entry->getName() . " (expected compressed entry size of " $entry->getName() . " (expected compressed entry size of "
. $entry->getCompressedSize() . " bytes, " . . $entry->getCompressedSize() . " bytes, " .
@@ -202,10 +203,10 @@ class ZipOutputStream implements ZipOutputStreamInterface
*/ */
protected function entryCommitChangesAndReturnContent(ZipEntry $entry) protected function entryCommitChangesAndReturnContent(ZipEntry $entry)
{ {
if (ZipEntry::UNKNOWN === $entry->getPlatform()) { if ($entry->getPlatform() === ZipEntry::UNKNOWN) {
$entry->setPlatform(ZipEntry::PLATFORM_UNIX); $entry->setPlatform(ZipEntry::PLATFORM_UNIX);
} }
if (ZipEntry::UNKNOWN === $entry->getTime()) { if ($entry->getTime() === ZipEntry::UNKNOWN) {
$entry->setTime(time()); $entry->setTime(time());
} }
$method = $entry->getMethod(); $method = $entry->getMethod();
@@ -214,7 +215,7 @@ class ZipOutputStream implements ZipOutputStreamInterface
// See appendix D of PKWARE's ZIP File Format Specification. // See appendix D of PKWARE's ZIP File Format Specification.
$utf8 = true; $utf8 = true;
if ($encrypted && null === $entry->getPassword()) { if ($encrypted && $entry->getPassword() === null) {
throw new ZipException("Can not password from entry " . $entry->getName()); throw new ZipException("Can not password from entry " . $entry->getName());
} }
@@ -232,12 +233,12 @@ class ZipOutputStream implements ZipOutputStreamInterface
$entry->setSize(strlen($entryContent)); $entry->setSize(strlen($entryContent));
$entry->setCrc(crc32($entryContent)); $entry->setCrc(crc32($entryContent));
if ($encrypted && ZipEntry::METHOD_WINZIP_AES === $method) { if ($encrypted && $method === ZipEntry::METHOD_WINZIP_AES) {
/** /**
* @var WinZipAesEntryExtraField $field * @var WinZipAesEntryExtraField $field
*/ */
$field = $extraFieldsCollection->get(WinZipAesEntryExtraField::getHeaderId()); $field = $extraFieldsCollection->get(WinZipAesEntryExtraField::getHeaderId());
if (null !== $field) { if ($field !== null) {
$method = $field->getMethod(); $method = $field->getMethod();
} }
} }
@@ -269,7 +270,7 @@ class ZipOutputStream implements ZipOutputStreamInterface
throw new ZipException($entry->getName() . " (unsupported compression method " . $method . ")"); throw new ZipException($entry->getName() . " (unsupported compression method " . $method . ")");
} }
if (ZipFileInterface::METHOD_DEFLATED === $method) { if ($method === ZipFileInterface::METHOD_DEFLATED) {
$bit1 = false; $bit1 = false;
$bit2 = false; $bit2 = false;
switch ($entry->getCompressionLevel()) { switch ($entry->getCompressionLevel()) {
@@ -302,7 +303,7 @@ class ZipOutputStream implements ZipOutputStreamInterface
$field->setKeyStrength($keyStrength); $field->setKeyStrength($keyStrength);
$field->setMethod($method); $field->setMethod($method);
$size = $entry->getSize(); $size = $entry->getSize();
if (20 <= $size && ZipFileInterface::METHOD_BZIP2 !== $method) { if ($size >= 20 && $method !== ZipFileInterface::METHOD_BZIP2) {
$field->setVendorVersion(WinZipAesEntryExtraField::VV_AE_1); $field->setVendorVersion(WinZipAesEntryExtraField::VV_AE_1);
} else { } else {
$field->setVendorVersion(WinZipAesEntryExtraField::VV_AE_2); $field->setVendorVersion(WinZipAesEntryExtraField::VV_AE_2);
@@ -343,7 +344,7 @@ class ZipOutputStream implements ZipOutputStreamInterface
*/ */
protected function determineBestCompressionMethod(ZipEntry $entry, $content) protected function determineBestCompressionMethod(ZipEntry $entry, $content)
{ {
if (null !== $content) { if ($content !== null) {
$entryContent = gzdeflate($content, $entry->getCompressionLevel()); $entryContent = gzdeflate($content, $entry->getCompressionLevel());
if (strlen($entryContent) < strlen($content)) { if (strlen($entryContent) < strlen($content)) {
$entry->setMethod(ZipFileInterface::METHOD_DEFLATED); $entry->setMethod(ZipFileInterface::METHOD_DEFLATED);
@@ -358,8 +359,6 @@ class ZipOutputStream implements ZipOutputStreamInterface
* Writes a Central File Header record. * Writes a Central File Header record.
* *
* @param OutputOffsetEntry $outEntry * @param OutputOffsetEntry $outEntry
* @throws RuntimeException
* @internal param OutPosEntry $entry
*/ */
protected function writeCentralDirectoryHeader(OutputOffsetEntry $outEntry) protected function writeCentralDirectoryHeader(OutputOffsetEntry $outEntry)
{ {
@@ -368,7 +367,7 @@ class ZipOutputStream implements ZipOutputStreamInterface
$size = $entry->getSize(); $size = $entry->getSize();
// This test MUST NOT include the CRC-32 because VV_AE_2 sets it to // This test MUST NOT include the CRC-32 because VV_AE_2 sets it to
// UNKNOWN! // UNKNOWN!
if (ZipEntry::UNKNOWN === ($compressedSize | $size)) { if (($compressedSize | $size) === ZipEntry::UNKNOWN) {
throw new RuntimeException("invalid entry"); throw new RuntimeException("invalid entry");
} }
$extra = $entry->getExtra(); $extra = $entry->getExtra();
@@ -415,11 +414,11 @@ class ZipOutputStream implements ZipOutputStreamInterface
); );
// file name (variable size) // file name (variable size)
fwrite($this->out, $entry->getName()); fwrite($this->out, $entry->getName());
if (0 < $extraSize) { if ($extraSize > 0) {
// extra field (variable size) // extra field (variable size)
fwrite($this->out, $extra); fwrite($this->out, $extra);
} }
if (0 < $commentLength) { if ($commentLength > 0) {
// file comment (variable size) // file comment (variable size)
fwrite($this->out, $entry->getComment()); fwrite($this->out, $entry->getComment());
} }

View File

@@ -15,16 +15,20 @@ class CryptoUtil
* *
* @param int $length * @param int $length
* @return string * @return string
* @throws RuntimeException
*/ */
final public static function randomBytes($length) final public static function randomBytes($length)
{ {
$length = (int)$length; $length = (int)$length;
if (function_exists('random_bytes')) { if (function_exists('random_bytes')) {
return random_bytes($length); try {
return random_bytes($length);
} catch (\Exception $e) {
throw new \RuntimeException("Could not generate a random string.");
}
} elseif (function_exists('openssl_random_pseudo_bytes')) { } elseif (function_exists('openssl_random_pseudo_bytes')) {
return openssl_random_pseudo_bytes($length); return openssl_random_pseudo_bytes($length);
} elseif (function_exists('mcrypt_create_iv')) { } elseif (function_exists('mcrypt_create_iv')) {
/** @noinspection PhpDeprecationInspection */
return mcrypt_create_iv($length); return mcrypt_create_iv($length);
} else { } else {
throw new RuntimeException('Extension openssl or mcrypt not loaded'); throw new RuntimeException('Extension openssl or mcrypt not loaded');

View File

@@ -12,7 +12,6 @@ use PhpZip\Util\StringUtil;
*/ */
class IgnoreFilesRecursiveFilterIterator extends \RecursiveFilterIterator class IgnoreFilesRecursiveFilterIterator extends \RecursiveFilterIterator
{ {
/** /**
* Ignore list files * Ignore list files
* *
@@ -65,6 +64,7 @@ class IgnoreFilesRecursiveFilterIterator extends \RecursiveFilterIterator
*/ */
public function getChildren() public function getChildren()
{ {
/** @noinspection PhpUndefinedMethodInspection */
return new self($this->getInnerIterator()->getChildren(), $this->ignoreFiles); return new self($this->getInnerIterator()->getChildren(), $this->ignoreFiles);
} }
} }

View File

@@ -2,8 +2,6 @@
namespace PhpZip\Util; namespace PhpZip\Util;
use PhpZip\Exception\ZipException;
/** /**
* Pack util * Pack util
* *
@@ -35,7 +33,6 @@ class PackUtil
/** /**
* @param string|int $value * @param string|int $value
* @return int * @return int
* @throws ZipException
*/ */
public static function unpackLongLE($value) public static function unpackLongLE($value)
{ {

View File

@@ -3,9 +3,9 @@
namespace PhpZip; namespace PhpZip;
use PhpZip\Exception\InvalidArgumentException; use PhpZip\Exception\InvalidArgumentException;
use PhpZip\Exception\ZipEntryNotFoundException;
use PhpZip\Exception\ZipException; use PhpZip\Exception\ZipException;
use PhpZip\Exception\ZipNotFoundEntry; use PhpZip\Exception\ZipUnsupportMethodException;
use PhpZip\Exception\ZipUnsupportMethod;
use PhpZip\Model\Entry\ZipNewEntry; use PhpZip\Model\Entry\ZipNewEntry;
use PhpZip\Model\ZipEntry; use PhpZip\Model\ZipEntry;
use PhpZip\Model\ZipEntryMatcher; use PhpZip\Model\ZipEntryMatcher;
@@ -34,8 +34,7 @@ use Psr\Http\Message\ResponseInterface;
class ZipFile implements ZipFileInterface class ZipFile implements ZipFileInterface
{ {
/** /**
* Allow compression methods. * @var int[] Allow compression methods.
* @var int[]
*/ */
private static $allowCompressionMethods = [ private static $allowCompressionMethods = [
self::METHOD_STORED, self::METHOD_STORED,
@@ -45,8 +44,7 @@ class ZipFile implements ZipFileInterface
]; ];
/** /**
* Allow encryption methods. * @var int[] Allow encryption methods.
* @var int[]
*/ */
private static $allowEncryptionMethods = [ private static $allowEncryptionMethods = [
self::ENCRYPTION_METHOD_TRADITIONAL, self::ENCRYPTION_METHOD_TRADITIONAL,
@@ -56,9 +54,7 @@ class ZipFile implements ZipFileInterface
]; ];
/** /**
* Default mime types. * @var array Default mime types.
*
* @var array
*/ */
private static $defaultMimeTypes = [ private static $defaultMimeTypes = [
'zip' => 'application/zip', 'zip' => 'application/zip',
@@ -69,11 +65,10 @@ class ZipFile implements ZipFileInterface
]; ];
/** /**
* Input seekable input stream. * @var ZipInputStreamInterface Input seekable input stream.
*
* @var ZipInputStreamInterface
*/ */
protected $inputStream; protected $inputStream;
/** /**
* @var ZipModel * @var ZipModel
*/ */
@@ -92,13 +87,12 @@ class ZipFile implements ZipFileInterface
* *
* @param string $filename * @param string $filename
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException if file doesn't exists. * @throws ZipException if can't open file.
* @throws ZipException if can't open file.
*/ */
public function openFile($filename) public function openFile($filename)
{ {
if (!file_exists($filename)) { if (!file_exists($filename)) {
throw new InvalidArgumentException("File $filename can't exists."); throw new ZipException("File $filename can't exists.");
} }
if (!($handle = @fopen($filename, 'rb'))) { if (!($handle = @fopen($filename, 'rb'))) {
throw new ZipException("File $filename can't open."); throw new ZipException("File $filename can't open.");
@@ -112,13 +106,12 @@ class ZipFile implements ZipFileInterface
* *
* @param string $data * @param string $data
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException if data not available. * @throws ZipException if can't open temp stream.
* @throws ZipException if can't open temp stream.
*/ */
public function openFromString($data) public function openFromString($data)
{ {
if (null === $data || strlen($data) === 0) { if ($data === null || strlen($data) === 0) {
throw new InvalidArgumentException("Data not available"); throw new InvalidArgumentException("Empty string passed");
} }
if (!($handle = fopen('php://temp', 'r+b'))) { if (!($handle = fopen('php://temp', 'r+b'))) {
throw new ZipException("Can't open temp stream."); throw new ZipException("Can't open temp stream.");
@@ -134,8 +127,7 @@ class ZipFile implements ZipFileInterface
* *
* @param resource $handle * @param resource $handle
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException Invalid stream resource * @throws ZipException
* or resource cannot seekable stream
*/ */
public function openFromStream($handle) public function openFromStream($handle)
{ {
@@ -143,11 +135,11 @@ class ZipFile implements ZipFileInterface
throw new InvalidArgumentException("Invalid stream resource."); throw new InvalidArgumentException("Invalid stream resource.");
} }
$type = get_resource_type($handle); $type = get_resource_type($handle);
if ('stream' !== $type) { if ($type !== 'stream') {
throw new InvalidArgumentException("Invalid resource type - $type."); throw new InvalidArgumentException("Invalid resource type - $type.");
} }
$meta = stream_get_meta_data($handle); $meta = stream_get_meta_data($handle);
if ('dir' === $meta['stream_type']) { if ($meta['stream_type'] === 'dir') {
throw new InvalidArgumentException("Invalid stream type - {$meta['stream_type']}."); throw new InvalidArgumentException("Invalid stream type - {$meta['stream_type']}.");
} }
if (!$meta['seekable']) { if (!$meta['seekable']) {
@@ -189,7 +181,6 @@ class ZipFile implements ZipFileInterface
* *
* @param null|string $comment * @param null|string $comment
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException Length comment out of range
*/ */
public function setArchiveComment($comment = null) public function setArchiveComment($comment = null)
{ {
@@ -204,7 +195,7 @@ class ZipFile implements ZipFileInterface
* *
* @param string $entryName * @param string $entryName
* @return bool * @return bool
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
*/ */
public function isDirectory($entryName) public function isDirectory($entryName)
{ {
@@ -216,7 +207,7 @@ class ZipFile implements ZipFileInterface
* *
* @param string $entryName * @param string $entryName
* @return string * @return string
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
*/ */
public function getEntryComment($entryName) public function getEntryComment($entryName)
{ {
@@ -229,7 +220,8 @@ class ZipFile implements ZipFileInterface
* @param string $entryName * @param string $entryName
* @param string|null $comment * @param string|null $comment
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipNotFoundEntry * @throws ZipException
* @throws ZipEntryNotFoundException
*/ */
public function setEntryComment($entryName, $comment = null) public function setEntryComment($entryName, $comment = null)
{ {
@@ -242,6 +234,7 @@ class ZipFile implements ZipFileInterface
* *
* @param string $entryName * @param string $entryName
* @return string * @return string
* @throws ZipException
*/ */
public function getEntryContents($entryName) public function getEntryContents($entryName)
{ {
@@ -264,7 +257,8 @@ class ZipFile implements ZipFileInterface
* *
* @param string|ZipEntry $entryName * @param string|ZipEntry $entryName
* @return ZipInfo * @return ZipInfo
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
* @throws ZipException
*/ */
public function getEntryInfo($entryName) public function getEntryInfo($entryName)
{ {
@@ -347,7 +341,7 @@ class ZipFile implements ZipFileInterface
chmod($dir, 0755); chmod($dir, 0755);
touch($dir, $entry->getTime()); touch($dir, $entry->getTime());
} }
if (false === file_put_contents($file, $entry->getEntryContent())) { if (file_put_contents($file, $entry->getEntryContent()) === false) {
throw new ZipException('Can not extract file ' . $entry->getName()); throw new ZipException('Can not extract file ' . $entry->getName());
} }
touch($file, $entry->getTime()); touch($file, $entry->getTime());
@@ -361,34 +355,36 @@ class ZipFile implements ZipFileInterface
* @param string $localName Zip entry name. * @param string $localName Zip entry name.
* @param string $contents String contents. * @param string $contents String contents.
* @param int|null $compressionMethod Compression method. * @param int|null $compressionMethod Compression method.
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use {@see ZipFile::METHOD_STORED}, {@see ZipFile::METHOD_DEFLATED} or {@see ZipFile::METHOD_BZIP2}.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException If incorrect data or entry name. * @throws ZipException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
*/ */
public function addFromString($localName, $contents, $compressionMethod = null) public function addFromString($localName, $contents, $compressionMethod = null)
{ {
if (null === $contents) { if ($contents === null) {
throw new InvalidArgumentException("Contents is null"); throw new InvalidArgumentException("Contents is null");
} }
$localName = (string)$localName; if ($localName === null) {
if (null === $localName || 0 === strlen($localName)) { throw new InvalidArgumentException("Entry name is null");
throw new InvalidArgumentException("Incorrect entry name " . $localName); }
$localName = ltrim((string)$localName, "\\/");
if (strlen($localName) === 0) {
throw new InvalidArgumentException("Empty entry name");
} }
$contents = (string)$contents; $contents = (string)$contents;
$length = strlen($contents); $length = strlen($contents);
if (null === $compressionMethod) { if ($compressionMethod === null) {
if ($length >= 512) { if ($length >= 512) {
$compressionMethod = ZipEntry::UNKNOWN; $compressionMethod = ZipEntry::UNKNOWN;
} else { } else {
$compressionMethod = ZipFileInterface::METHOD_STORED; $compressionMethod = self::METHOD_STORED;
} }
} elseif (!in_array($compressionMethod, self::$allowCompressionMethods, true)) { } elseif (!in_array($compressionMethod, self::$allowCompressionMethods, true)) {
throw new ZipUnsupportMethod('Unsupported compression method ' . $compressionMethod); throw new ZipUnsupportMethodException('Unsupported compression method ' . $compressionMethod);
} }
$externalAttributes = 0100644 << 16; $externalAttributes = 0100644 << 16;
@@ -411,45 +407,44 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
*/ */
public function addFile($filename, $localName = null, $compressionMethod = null) public function addFile($filename, $localName = null, $compressionMethod = null)
{ {
if (null === $filename) { if ($filename === null) {
throw new InvalidArgumentException("Filename is null"); throw new InvalidArgumentException("Filename is null");
} }
if (!is_file($filename)) { if (!is_file($filename)) {
throw new InvalidArgumentException("File $filename is not exists"); throw new ZipException("File $filename is not exists");
} }
if (null === $compressionMethod) { if ($compressionMethod === null) {
if (function_exists('mime_content_type')) { if (function_exists('mime_content_type')) {
$mimeType = @mime_content_type($filename); $mimeType = @mime_content_type($filename);
$type = strtok($mimeType, '/'); $type = strtok($mimeType, '/');
if ('image' === $type) { if ($type === 'image') {
$compressionMethod = ZipFileInterface::METHOD_STORED; $compressionMethod = self::METHOD_STORED;
} elseif ('text' === $type && filesize($filename) < 150) { } elseif ($type === 'text' && filesize($filename) < 150) {
$compressionMethod = ZipFileInterface::METHOD_STORED; $compressionMethod = self::METHOD_STORED;
} else { } else {
$compressionMethod = ZipEntry::UNKNOWN; $compressionMethod = ZipEntry::UNKNOWN;
} }
} elseif (@filesize($filename) >= 512) { } elseif (filesize($filename) >= 512) {
$compressionMethod = ZipEntry::UNKNOWN; $compressionMethod = ZipEntry::UNKNOWN;
} else { } else {
$compressionMethod = ZipFileInterface::METHOD_STORED; $compressionMethod = self::METHOD_STORED;
} }
} elseif (!in_array($compressionMethod, self::$allowCompressionMethods, true)) { } elseif (!in_array($compressionMethod, self::$allowCompressionMethods, true)) {
throw new ZipUnsupportMethod('Unsupported method ' . $compressionMethod); throw new ZipUnsupportMethodException('Unsupported compression method ' . $compressionMethod);
} }
if (!($handle = @fopen($filename, 'rb'))) { if (!($handle = @fopen($filename, 'rb'))) {
throw new InvalidArgumentException('File ' . $filename . ' can not open.'); throw new ZipException('File ' . $filename . ' can not open.');
} }
if (null === $localName) { if ($localName === null) {
$localName = basename($filename); $localName = basename($filename);
} }
$this->addFromStream($handle, $localName, $compressionMethod); $this->addFromStream($handle, $localName, $compressionMethod);
@@ -466,8 +461,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
@@ -475,22 +469,25 @@ class ZipFile implements ZipFileInterface
public function addFromStream($stream, $localName, $compressionMethod = null) public function addFromStream($stream, $localName, $compressionMethod = null)
{ {
if (!is_resource($stream)) { if (!is_resource($stream)) {
throw new InvalidArgumentException("stream is not resource"); throw new InvalidArgumentException("Stream is not resource");
} }
$localName = (string)$localName; if ($localName === null) {
if (empty($localName)) { throw new InvalidArgumentException("Entry name is null");
throw new InvalidArgumentException("Incorrect entry name " . $localName); }
$localName = ltrim((string)$localName, "\\/");
if (strlen($localName) === 0) {
throw new InvalidArgumentException("Empty entry name");
} }
$fstat = fstat($stream); $fstat = fstat($stream);
$length = $fstat['size']; $length = $fstat['size'];
if (null === $compressionMethod) { if ($compressionMethod === null) {
if ($length >= 512) { if ($length >= 512) {
$compressionMethod = ZipEntry::UNKNOWN; $compressionMethod = ZipEntry::UNKNOWN;
} else { } else {
$compressionMethod = ZipFileInterface::METHOD_STORED; $compressionMethod = self::METHOD_STORED;
} }
} elseif (!in_array($compressionMethod, self::$allowCompressionMethods, true)) { } elseif (!in_array($compressionMethod, self::$allowCompressionMethods, true)) {
throw new ZipUnsupportMethod('Unsupported method ' . $compressionMethod); throw new ZipUnsupportMethodException('Unsupported method ' . $compressionMethod);
} }
$mode = sprintf('%o', $fstat['mode']); $mode = sprintf('%o', $fstat['mode']);
@@ -511,21 +508,24 @@ class ZipFile implements ZipFileInterface
* *
* @param string $dirName * @param string $dirName
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
*/ */
public function addEmptyDir($dirName) public function addEmptyDir($dirName)
{ {
$dirName = (string)$dirName; if ($dirName === null) {
if (strlen($dirName) === 0) { throw new InvalidArgumentException("Dir name is null");
throw new InvalidArgumentException("DirName empty");
} }
$dirName = rtrim($dirName, '/') . '/'; $dirName = ltrim((string)$dirName, "\\/");
if (strlen($dirName) === 0) {
throw new InvalidArgumentException("Empty dir name");
}
$dirName = rtrim($dirName, '\\/') . '/';
$externalAttributes = 040755 << 16; $externalAttributes = 040755 << 16;
$entry = new ZipNewEntry(); $entry = new ZipNewEntry();
$entry->setName($dirName); $entry->setName($dirName);
$entry->setTime(time()); $entry->setTime(time());
$entry->setMethod(ZipFileInterface::METHOD_STORED); $entry->setMethod(self::METHOD_STORED);
$entry->setSize(0); $entry->setSize(0);
$entry->setCompressedSize(0); $entry->setCompressedSize(0);
$entry->setCrc(0); $entry->setCrc(0);
@@ -544,16 +544,19 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
*/ */
public function addDir($inputDir, $localPath = "/", $compressionMethod = null) public function addDir($inputDir, $localPath = "/", $compressionMethod = null)
{ {
if ($inputDir === null) {
throw new InvalidArgumentException('Input dir is null');
}
$inputDir = (string)$inputDir; $inputDir = (string)$inputDir;
if (null === $inputDir || strlen($inputDir) === 0) { if (strlen($inputDir) === 0) {
throw new InvalidArgumentException('Input dir empty'); throw new InvalidArgumentException('Input dir empty');
} }
if (!is_dir($inputDir)) { if (!is_dir($inputDir)) {
throw new InvalidArgumentException('Directory ' . $inputDir . ' can\'t exists'); throw new ZipException('Directory ' . $inputDir . ' can\'t exists');
} }
$inputDir = rtrim($inputDir, '/\\') . DIRECTORY_SEPARATOR; $inputDir = rtrim($inputDir, '/\\') . DIRECTORY_SEPARATOR;
@@ -570,8 +573,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
@@ -600,8 +602,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
@@ -613,8 +614,8 @@ class ZipFile implements ZipFileInterface
) )
{ {
$localPath = (string)$localPath; $localPath = (string)$localPath;
if (null !== $localPath && 0 !== strlen($localPath)) { if (strlen($localPath) !== 0) {
$localPath = rtrim($localPath, '/'); $localPath = trim($localPath, '\\/');
} else { } else {
$localPath = ""; $localPath = "";
} }
@@ -629,10 +630,10 @@ class ZipFile implements ZipFileInterface
$files = []; $files = [];
foreach ($iterator as $file) { foreach ($iterator as $file) {
if ($file instanceof \SplFileInfo) { if ($file instanceof \SplFileInfo) {
if ('..' === $file->getBasename()) { if ($file->getBasename() === '..') {
continue; continue;
} }
if ('.' === $file->getBasename()) { if ($file->getBasename() === '.') {
$files[] = dirname($file->getPathname()); $files[] = dirname($file->getPathname());
} else { } else {
$files[] = $file->getPathname(); $files[] = $file->getPathname();
@@ -647,9 +648,9 @@ class ZipFile implements ZipFileInterface
$path = array_shift($files); $path = array_shift($files);
foreach ($files as $file) { foreach ($files as $file) {
$relativePath = str_replace($path, $localPath, $file); $relativePath = str_replace($path, $localPath, $file);
$relativePath = ltrim($relativePath, '/'); $relativePath = ltrim($relativePath, '\\/');
if (is_dir($file)) { if (is_dir($file) && FilesUtil::isEmptyDir($file)) {
FilesUtil::isEmptyDir($file) && $this->addEmptyDir($relativePath); $this->addEmptyDir($relativePath);
} elseif (is_file($file)) { } elseif (is_file($file)) {
$this->addFile($file, $relativePath, $compressionMethod); $this->addFile($file, $relativePath, $compressionMethod);
} }
@@ -667,7 +668,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
* @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
*/ */
public function addFilesFromGlob($inputDir, $globPattern, $localPath = '/', $compressionMethod = null) public function addFilesFromGlob($inputDir, $globPattern, $localPath = '/', $compressionMethod = null)
@@ -686,7 +687,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
* @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
*/ */
private function addGlob( private function addGlob(
@@ -698,11 +699,11 @@ class ZipFile implements ZipFileInterface
) )
{ {
$inputDir = (string)$inputDir; $inputDir = (string)$inputDir;
if (null === $inputDir || 0 === strlen($inputDir)) { if (strlen($inputDir) === 0) {
throw new InvalidArgumentException('Input dir empty'); throw new InvalidArgumentException('Input dir empty');
} }
if (!is_dir($inputDir)) { if (!is_dir($inputDir)) {
throw new InvalidArgumentException('Directory ' . $inputDir . ' can\'t exists'); throw new ZipException('Directory ' . $inputDir . ' can\'t exists');
} }
$globPattern = (string)$globPattern; $globPattern = (string)$globPattern;
if (empty($globPattern)) { if (empty($globPattern)) {
@@ -713,11 +714,11 @@ class ZipFile implements ZipFileInterface
$globPattern = $inputDir . $globPattern; $globPattern = $inputDir . $globPattern;
$filesFound = FilesUtil::globFileSearch($globPattern, GLOB_BRACE, $recursive); $filesFound = FilesUtil::globFileSearch($globPattern, GLOB_BRACE, $recursive);
if (false === $filesFound || empty($filesFound)) { if ($filesFound === false || empty($filesFound)) {
return $this; return $this;
} }
if (!empty($localPath) && is_string($localPath)) { if (!empty($localPath) && is_string($localPath)) {
$localPath = rtrim($localPath, '/') . '/'; $localPath = trim($localPath, '/\\') . '/';
} else { } else {
$localPath = "/"; $localPath = "/";
} }
@@ -727,9 +728,9 @@ class ZipFile implements ZipFileInterface
*/ */
foreach ($filesFound as $file) { foreach ($filesFound as $file) {
$filename = str_replace($inputDir, $localPath, $file); $filename = str_replace($inputDir, $localPath, $file);
$filename = ltrim($filename, '/'); $filename = ltrim($filename, '\\/');
if (is_dir($file)) { if (is_dir($file) && FilesUtil::isEmptyDir($file)) {
FilesUtil::isEmptyDir($file) && $this->addEmptyDir($filename); $this->addEmptyDir($filename);
} elseif (is_file($file)) { } elseif (is_file($file)) {
$this->addFile($file, $filename, $compressionMethod); $this->addFile($file, $filename, $compressionMethod);
} }
@@ -747,7 +748,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
* @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
*/ */
public function addFilesFromGlobRecursive($inputDir, $globPattern, $localPath = '/', $compressionMethod = null) public function addFilesFromGlobRecursive($inputDir, $globPattern, $localPath = '/', $compressionMethod = null)
@@ -765,6 +766,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipException
* @internal param bool $recursive Recursive search. * @internal param bool $recursive Recursive search.
*/ */
public function addFilesFromRegex($inputDir, $regexPattern, $localPath = "/", $compressionMethod = null) public function addFilesFromRegex($inputDir, $regexPattern, $localPath = "/", $compressionMethod = null)
@@ -783,7 +785,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipException
*/ */
private function addRegex( private function addRegex(
$inputDir, $inputDir,
@@ -798,7 +800,7 @@ class ZipFile implements ZipFileInterface
throw new InvalidArgumentException("regex pattern empty"); throw new InvalidArgumentException("regex pattern empty");
} }
$inputDir = (string)$inputDir; $inputDir = (string)$inputDir;
if (null === $inputDir || 0 === strlen($inputDir)) { if (strlen($inputDir) === 0) {
throw new InvalidArgumentException('Input dir empty'); throw new InvalidArgumentException('Input dir empty');
} }
if (!is_dir($inputDir)) { if (!is_dir($inputDir)) {
@@ -807,11 +809,11 @@ class ZipFile implements ZipFileInterface
$inputDir = rtrim($inputDir, '/\\') . DIRECTORY_SEPARATOR; $inputDir = rtrim($inputDir, '/\\') . DIRECTORY_SEPARATOR;
$files = FilesUtil::regexFileSearch($inputDir, $regexPattern, $recursive); $files = FilesUtil::regexFileSearch($inputDir, $regexPattern, $recursive);
if (false === $files || empty($files)) { if (empty($files)) {
return $this; return $this;
} }
if (!empty($localPath) && is_string($localPath)) { if (!empty($localPath) && is_string($localPath)) {
$localPath = rtrim($localPath, '/') . '/'; $localPath = trim($localPath, '\\/') . '/';
} else { } else {
$localPath = "/"; $localPath = "/";
} }
@@ -822,9 +824,9 @@ class ZipFile implements ZipFileInterface
*/ */
foreach ($files as $file) { foreach ($files as $file) {
$filename = str_replace($inputDir, $localPath, $file); $filename = str_replace($inputDir, $localPath, $file);
$filename = ltrim($filename, '/'); $filename = ltrim($filename, '\\/');
if (is_dir($file)) { if (is_dir($file) && FilesUtil::isEmptyDir($file)) {
FilesUtil::isEmptyDir($file) && $this->addEmptyDir($filename); $this->addEmptyDir($filename);
} elseif (is_file($file)) { } elseif (is_file($file)) {
$this->addFile($file, $filename, $compressionMethod); $this->addFile($file, $filename, $compressionMethod);
} }
@@ -842,6 +844,7 @@ class ZipFile implements ZipFileInterface
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipException
* @internal param bool $recursive Recursive search. * @internal param bool $recursive Recursive search.
*/ */
public function addFilesFromRegexRecursive($inputDir, $regexPattern, $localPath = "/", $compressionMethod = null) public function addFilesFromRegexRecursive($inputDir, $regexPattern, $localPath = "/", $compressionMethod = null)
@@ -869,14 +872,16 @@ class ZipFile implements ZipFileInterface
* @param string $oldName Old entry name. * @param string $oldName Old entry name.
* @param string $newName New entry name. * @param string $newName New entry name.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException *
* @throws ZipNotFoundEntry * @throws ZipException
*/ */
public function rename($oldName, $newName) public function rename($oldName, $newName)
{ {
if (null === $oldName || null === $newName) { if ($oldName === null || $newName === null) {
throw new InvalidArgumentException("name is null"); throw new InvalidArgumentException("name is null");
} }
$oldName = ltrim((string)$oldName, '\\/');
$newName = ltrim((string)$newName, '\\/');
if ($oldName !== $newName) { if ($oldName !== $newName) {
$this->zipModel->renameEntry($oldName, $newName); $this->zipModel->renameEntry($oldName, $newName);
} }
@@ -888,13 +893,13 @@ class ZipFile implements ZipFileInterface
* *
* @param string $entryName Zip Entry name. * @param string $entryName Zip Entry name.
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipNotFoundEntry If entry not found. * @throws ZipEntryNotFoundException If entry not found.
*/ */
public function deleteFromName($entryName) public function deleteFromName($entryName)
{ {
$entryName = (string)$entryName; $entryName = ltrim((string)$entryName, '\\/');
if (!$this->zipModel->deleteEntry($entryName)) { if (!$this->zipModel->deleteEntry($entryName)) {
throw new ZipNotFoundEntry("Entry " . $entryName . ' not found!'); throw new ZipEntryNotFoundException($entryName);
} }
return $this; return $this;
} }
@@ -904,12 +909,11 @@ class ZipFile implements ZipFileInterface
* *
* @param string $globPattern Glob pattern * @param string $globPattern Glob pattern
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
*/ */
public function deleteFromGlob($globPattern) public function deleteFromGlob($globPattern)
{ {
if (null === $globPattern || !is_string($globPattern) || empty($globPattern)) { if ($globPattern === null || !is_string($globPattern) || empty($globPattern)) {
throw new InvalidArgumentException("Glob pattern is empty"); throw new InvalidArgumentException("Glob pattern is empty");
} }
$globPattern = '~' . FilesUtil::convertGlobToRegEx($globPattern) . '~si'; $globPattern = '~' . FilesUtil::convertGlobToRegEx($globPattern) . '~si';
@@ -922,11 +926,10 @@ class ZipFile implements ZipFileInterface
* *
* @param string $regexPattern Regex pattern * @param string $regexPattern Regex pattern
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
*/ */
public function deleteFromRegex($regexPattern) public function deleteFromRegex($regexPattern)
{ {
if (null === $regexPattern || !is_string($regexPattern) || empty($regexPattern)) { if ($regexPattern === null || !is_string($regexPattern) || empty($regexPattern)) {
throw new InvalidArgumentException("Regex pattern is empty."); throw new InvalidArgumentException("Regex pattern is empty.");
} }
$this->matcher()->match($regexPattern)->delete(); $this->matcher()->match($regexPattern)->delete();
@@ -948,19 +951,18 @@ class ZipFile implements ZipFileInterface
* *
* @param int $compressionLevel * @param int $compressionLevel
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @see ZipFileInterface::LEVEL_DEFAULT_COMPRESSION * @see ZipFileInterface::LEVEL_DEFAULT_COMPRESSION
* @see ZipFileInterface::LEVEL_SUPER_FAST * @see ZipFileInterface::LEVEL_SUPER_FAST
* @see ZipFileInterface::LEVEL_FAST * @see ZipFileInterface::LEVEL_FAST
* @see ZipFileInterface::LEVEL_BEST_COMPRESSION * @see ZipFileInterface::LEVEL_BEST_COMPRESSION
*/ */
public function setCompressionLevel($compressionLevel = ZipFileInterface::LEVEL_DEFAULT_COMPRESSION) public function setCompressionLevel($compressionLevel = self::LEVEL_DEFAULT_COMPRESSION)
{ {
if ($compressionLevel < ZipFileInterface::LEVEL_DEFAULT_COMPRESSION || if ($compressionLevel < self::LEVEL_DEFAULT_COMPRESSION ||
$compressionLevel > ZipFileInterface::LEVEL_BEST_COMPRESSION $compressionLevel > self::LEVEL_BEST_COMPRESSION
) { ) {
throw new InvalidArgumentException('Invalid compression level. Minimum level ' . throw new InvalidArgumentException('Invalid compression level. Minimum level ' .
ZipFileInterface::LEVEL_DEFAULT_COMPRESSION . '. Maximum level ' . ZipFileInterface::LEVEL_BEST_COMPRESSION); self::LEVEL_DEFAULT_COMPRESSION . '. Maximum level ' . self::LEVEL_BEST_COMPRESSION);
} }
$this->matcher()->all()->invoke(function ($entry) use ($compressionLevel) { $this->matcher()->all()->invoke(function ($entry) use ($compressionLevel) {
$this->setCompressionLevelEntry($entry, $compressionLevel); $this->setCompressionLevelEntry($entry, $compressionLevel);
@@ -980,15 +982,15 @@ class ZipFile implements ZipFileInterface
*/ */
public function setCompressionLevelEntry($entryName, $compressionLevel) public function setCompressionLevelEntry($entryName, $compressionLevel)
{ {
if (null !== $compressionLevel) { if ($compressionLevel !== null) {
if ($compressionLevel < ZipFileInterface::LEVEL_DEFAULT_COMPRESSION || if ($compressionLevel < ZipFileInterface::LEVEL_DEFAULT_COMPRESSION ||
$compressionLevel > ZipFileInterface::LEVEL_BEST_COMPRESSION $compressionLevel > ZipFileInterface::LEVEL_BEST_COMPRESSION
) { ) {
throw new InvalidArgumentException('Invalid compression level. Minimum level ' . throw new InvalidArgumentException('Invalid compression level. Minimum level ' .
ZipFileInterface::LEVEL_DEFAULT_COMPRESSION . '. Maximum level ' . ZipFileInterface::LEVEL_BEST_COMPRESSION); self::LEVEL_DEFAULT_COMPRESSION . '. Maximum level ' . self::LEVEL_BEST_COMPRESSION);
} }
$entry = $this->zipModel->getEntry($entryName); $entry = $this->zipModel->getEntry($entryName);
if ($entry->getCompressionLevel() !== $compressionLevel) { if ($compressionLevel !== $entry->getCompressionLevel()) {
$entry = $this->zipModel->getEntryForChanges($entry); $entry = $this->zipModel->getEntryForChanges($entry);
$entry->setCompressionLevel($compressionLevel); $entry->setCompressionLevel($compressionLevel);
} }
@@ -1008,10 +1010,10 @@ class ZipFile implements ZipFileInterface
public function setCompressionMethodEntry($entryName, $compressionMethod) public function setCompressionMethodEntry($entryName, $compressionMethod)
{ {
if (!in_array($compressionMethod, self::$allowCompressionMethods, true)) { if (!in_array($compressionMethod, self::$allowCompressionMethods, true)) {
throw new ZipUnsupportMethod('Unsupported method ' . $compressionMethod); throw new ZipUnsupportMethodException('Unsupported method ' . $compressionMethod);
} }
$entry = $this->zipModel->getEntry($entryName); $entry = $this->zipModel->getEntry($entryName);
if ($entry->getMethod() !== $compressionMethod) { if ($compressionMethod !== $entry->getMethod()) {
$this->zipModel $this->zipModel
->getEntryForChanges($entry) ->getEntryForChanges($entry)
->setMethod($compressionMethod); ->setMethod($compressionMethod);
@@ -1037,6 +1039,7 @@ class ZipFile implements ZipFileInterface
* *
* @param string $password Password * @param string $password Password
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipException
* @deprecated using ZipFileInterface::setReadPassword() * @deprecated using ZipFileInterface::setReadPassword()
*/ */
public function withReadPassword($password) public function withReadPassword($password)
@@ -1049,6 +1052,7 @@ class ZipFile implements ZipFileInterface
* *
* @param string $password Password * @param string $password Password
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipException
*/ */
public function setReadPassword($password) public function setReadPassword($password)
{ {
@@ -1062,6 +1066,7 @@ class ZipFile implements ZipFileInterface
* @param string $entryName * @param string $entryName
* @param string $password Password * @param string $password Password
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipException
*/ */
public function setReadPasswordEntry($entryName, $password) public function setReadPasswordEntry($entryName, $password)
{ {
@@ -1076,6 +1081,7 @@ class ZipFile implements ZipFileInterface
* @param int|null $encryptionMethod Encryption method * @param int|null $encryptionMethod Encryption method
* @return ZipFileInterface * @return ZipFileInterface
* @deprecated using ZipFileInterface::setPassword() * @deprecated using ZipFileInterface::setPassword()
* @throws ZipException
*/ */
public function withNewPassword($password, $encryptionMethod = self::ENCRYPTION_METHOD_WINZIP_AES_256) public function withNewPassword($password, $encryptionMethod = self::ENCRYPTION_METHOD_WINZIP_AES_256)
{ {
@@ -1093,9 +1099,9 @@ class ZipFile implements ZipFileInterface
public function setPassword($password, $encryptionMethod = self::ENCRYPTION_METHOD_WINZIP_AES_256) public function setPassword($password, $encryptionMethod = self::ENCRYPTION_METHOD_WINZIP_AES_256)
{ {
$this->zipModel->setWritePassword($password); $this->zipModel->setWritePassword($password);
if (null !== $encryptionMethod) { if ($encryptionMethod !== null) {
if (!in_array($encryptionMethod, self::$allowEncryptionMethods)) { if (!in_array($encryptionMethod, self::$allowEncryptionMethods, true)) {
throw new ZipException('Invalid encryption method'); throw new ZipException('Invalid encryption method "' . $encryptionMethod . '"');
} }
$this->zipModel->setEncryptionMethod($encryptionMethod); $this->zipModel->setEncryptionMethod($encryptionMethod);
} }
@@ -1113,9 +1119,9 @@ class ZipFile implements ZipFileInterface
*/ */
public function setPasswordEntry($entryName, $password, $encryptionMethod = null) public function setPasswordEntry($entryName, $password, $encryptionMethod = null)
{ {
if (null !== $encryptionMethod) { if ($encryptionMethod !== null) {
if (!in_array($encryptionMethod, self::$allowEncryptionMethods)) { if (!in_array($encryptionMethod, self::$allowEncryptionMethods, true)) {
throw new ZipException('Invalid encryption method'); throw new ZipException('Invalid encryption method "' . $encryptionMethod . '"');
} }
} }
$this->matcher()->add($entryName)->setPassword($password, $encryptionMethod); $this->matcher()->add($entryName)->setPassword($password, $encryptionMethod);
@@ -1190,7 +1196,6 @@ class ZipFile implements ZipFileInterface
* *
* @param string $filename Output filename * @param string $filename Output filename
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @throws ZipException * @throws ZipException
*/ */
public function saveAsFile($filename) public function saveAsFile($filename)
@@ -1204,6 +1209,9 @@ class ZipFile implements ZipFileInterface
$this->saveAsStream($handle); $this->saveAsStream($handle);
if (!@rename($tempFilename, $filename)) { if (!@rename($tempFilename, $filename)) {
if (is_file($tempFilename)) {
unlink($tempFilename);
}
throw new ZipException('Can not move ' . $tempFilename . ' to ' . $filename); throw new ZipException('Can not move ' . $tempFilename . ' to ' . $filename);
} }
return $this; return $this;
@@ -1234,7 +1242,7 @@ class ZipFile implements ZipFileInterface
* @param string $outputFilename Output filename * @param string $outputFilename Output filename
* @param string|null $mimeType Mime-Type * @param string|null $mimeType Mime-Type
* @param bool $attachment Http Header 'Content-Disposition' if true then attachment otherwise inline * @param bool $attachment Http Header 'Content-Disposition' if true then attachment otherwise inline
* @throws InvalidArgumentException * @throws ZipException
*/ */
public function outputAsAttachment($outputFilename, $mimeType = null, $attachment = true) public function outputAsAttachment($outputFilename, $mimeType = null, $attachment = true)
{ {
@@ -1273,7 +1281,7 @@ class ZipFile implements ZipFileInterface
* @param string|null $mimeType Mime-Type * @param string|null $mimeType Mime-Type
* @param bool $attachment Http Header 'Content-Disposition' if true then attachment otherwise inline * @param bool $attachment Http Header 'Content-Disposition' if true then attachment otherwise inline
* @return ResponseInterface * @return ResponseInterface
* @throws InvalidArgumentException * @throws ZipException
*/ */
public function outputAsResponse(ResponseInterface $response, $outputFilename, $mimeType = null, $attachment = true) public function outputAsResponse(ResponseInterface $response, $outputFilename, $mimeType = null, $attachment = true)
{ {
@@ -1310,7 +1318,8 @@ class ZipFile implements ZipFileInterface
} }
/** /**
* @param $handle * @param resource $handle
* @throws ZipException
*/ */
protected function writeZipToStream($handle) protected function writeZipToStream($handle)
{ {
@@ -1323,7 +1332,7 @@ class ZipFile implements ZipFileInterface
/** /**
* Returns the zip archive as a string. * Returns the zip archive as a string.
* @return string * @return string
* @throws InvalidArgumentException * @throws ZipException
*/ */
public function outputAsString() public function outputAsString()
{ {
@@ -1349,7 +1358,7 @@ class ZipFile implements ZipFileInterface
*/ */
public function close() public function close()
{ {
if (null !== $this->inputStream) { if ($this->inputStream !== null) {
$this->inputStream->close(); $this->inputStream->close();
$this->inputStream = null; $this->inputStream = null;
$this->zipModel = new ZipModel(); $this->zipModel = new ZipModel();
@@ -1363,22 +1372,22 @@ class ZipFile implements ZipFileInterface
*/ */
public function rewrite() public function rewrite()
{ {
if (null === $this->inputStream) { if ($this->inputStream === null) {
throw new ZipException('input stream is null'); throw new ZipException('input stream is null');
} }
$meta = stream_get_meta_data($this->inputStream->getStream()); $meta = stream_get_meta_data($this->inputStream->getStream());
$content = $this->outputAsString(); $content = $this->outputAsString();
$this->close(); $this->close();
if ('plainfile' === $meta['wrapper_type']) { if ($meta['wrapper_type'] === 'plainfile') {
/** /**
* @var resource $uri * @var resource $uri
*/ */
$uri = $meta['uri']; $uri = $meta['uri'];
if (file_put_contents($uri, $content) === false) { if (file_put_contents($uri, $content) === false) {
throw new ZipException("Can not overwrite the zip file in the {$uri} file."); throw new ZipException("Can not overwrite the zip file in the $uri file.");
} }
if (!($handle = @fopen($uri, 'rb'))) { if (!($handle = @fopen($uri, 'rb'))) {
throw new ZipException("File {$uri} can't open."); throw new ZipException("File $uri can't open.");
} }
return $this->openFromStream($handle); return $this->openFromStream($handle);
} }
@@ -1398,7 +1407,7 @@ class ZipFile implements ZipFileInterface
* @link http://php.net/manual/en/arrayaccess.offsetset.php * @link http://php.net/manual/en/arrayaccess.offsetset.php
* @param string $entryName The offset to assign the value to. * @param string $entryName The offset to assign the value to.
* @param mixed $contents The value to set. * @param mixed $contents The value to set.
* @throws InvalidArgumentException * @throws ZipException
* @see ZipFile::addFromString * @see ZipFile::addFromString
* @see ZipFile::addEmptyDir * @see ZipFile::addEmptyDir
* @see ZipFile::addFile * @see ZipFile::addFile
@@ -1406,10 +1415,10 @@ class ZipFile implements ZipFileInterface
*/ */
public function offsetSet($entryName, $contents) public function offsetSet($entryName, $contents)
{ {
if (null === $entryName) { if ($entryName === null) {
throw new InvalidArgumentException('entryName is null'); throw new InvalidArgumentException('entryName is null');
} }
$entryName = (string)$entryName; $entryName = ltrim((string)$entryName, "\\/");
if (strlen($entryName) === 0) { if (strlen($entryName) === 0) {
throw new InvalidArgumentException('entryName is empty'); throw new InvalidArgumentException('entryName is empty');
} }
@@ -1426,8 +1435,7 @@ class ZipFile implements ZipFileInterface
} elseif (is_resource($contents)) { } elseif (is_resource($contents)) {
$this->addFromStream($contents, $entryName); $this->addFromStream($contents, $entryName);
} else { } else {
$contents = (string)$contents; $this->addFromString($entryName, (string)$contents);
$this->addFromString($entryName, $contents);
} }
} }
@@ -1435,7 +1443,7 @@ class ZipFile implements ZipFileInterface
* Offset to unset * Offset to unset
* @link http://php.net/manual/en/arrayaccess.offsetunset.php * @link http://php.net/manual/en/arrayaccess.offsetunset.php
* @param string $entryName The offset to unset. * @param string $entryName The offset to unset.
* @throws ZipUnsupportMethod * @throws ZipEntryNotFoundException
*/ */
public function offsetUnset($entryName) public function offsetUnset($entryName)
{ {
@@ -1447,6 +1455,7 @@ class ZipFile implements ZipFileInterface
* @link http://php.net/manual/en/iterator.current.php * @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type. * @return mixed Can return any type.
* @since 5.0.0 * @since 5.0.0
* @throws ZipException
*/ */
public function current() public function current()
{ {
@@ -1458,7 +1467,7 @@ class ZipFile implements ZipFileInterface
* @link http://php.net/manual/en/arrayaccess.offsetget.php * @link http://php.net/manual/en/arrayaccess.offsetget.php
* @param string $entryName The offset to retrieve. * @param string $entryName The offset to retrieve.
* @return string|null * @return string|null
* @throws ZipNotFoundEntry * @throws ZipException
*/ */
public function offsetGet($entryName) public function offsetGet($entryName)
{ {

View File

@@ -2,10 +2,8 @@
namespace PhpZip; namespace PhpZip;
use PhpZip\Exception\InvalidArgumentException; use PhpZip\Exception\ZipEntryNotFoundException;
use PhpZip\Exception\ZipException; use PhpZip\Exception\ZipException;
use PhpZip\Exception\ZipNotFoundEntry;
use PhpZip\Exception\ZipUnsupportMethod;
use PhpZip\Model\ZipEntry; use PhpZip\Model\ZipEntry;
use PhpZip\Model\ZipEntryMatcher; use PhpZip\Model\ZipEntryMatcher;
use PhpZip\Model\ZipInfo; use PhpZip\Model\ZipInfo;
@@ -87,7 +85,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $filename * @param string $filename
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException if file doesn't exists.
* @throws ZipException if can't open file. * @throws ZipException if can't open file.
*/ */
public function openFile($filename); public function openFile($filename);
@@ -97,7 +94,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $data * @param string $data
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException if data not available.
* @throws ZipException if can't open temp stream. * @throws ZipException if can't open temp stream.
*/ */
public function openFromString($data); public function openFromString($data);
@@ -107,8 +103,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param resource $handle * @param resource $handle
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException Invalid stream resource
* or resource cannot seekable stream
*/ */
public function openFromStream($handle); public function openFromStream($handle);
@@ -129,7 +123,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param null|string $comment * @param null|string $comment
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException Length comment out of range
*/ */
public function setArchiveComment($comment = null); public function setArchiveComment($comment = null);
@@ -140,7 +133,7 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $entryName * @param string $entryName
* @return bool * @return bool
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
*/ */
public function isDirectory($entryName); public function isDirectory($entryName);
@@ -149,7 +142,7 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $entryName * @param string $entryName
* @return string * @return string
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
*/ */
public function getEntryComment($entryName); public function getEntryComment($entryName);
@@ -159,7 +152,7 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* @param string $entryName * @param string $entryName
* @param string|null $comment * @param string|null $comment
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
*/ */
public function setEntryComment($entryName, $comment = null); public function setEntryComment($entryName, $comment = null);
@@ -184,7 +177,7 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string|ZipEntry $entryName * @param string|ZipEntry $entryName
* @return ZipInfo * @return ZipInfo
* @throws ZipNotFoundEntry * @throws ZipEntryNotFoundException
*/ */
public function getEntryInfo($entryName); public function getEntryInfo($entryName);
@@ -222,8 +215,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException If incorrect data or entry name.
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
@@ -239,8 +230,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
@@ -256,8 +245,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
@@ -269,7 +256,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $dirName * @param string $dirName
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
*/ */
public function addEmptyDir($dirName); public function addEmptyDir($dirName);
@@ -282,7 +268,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
*/ */
public function addDir($inputDir, $localPath = "/", $compressionMethod = null); public function addDir($inputDir, $localPath = "/", $compressionMethod = null);
@@ -295,8 +280,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
@@ -312,8 +295,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @throws ZipUnsupportMethod
* @see ZipFileInterface::METHOD_STORED * @see ZipFileInterface::METHOD_STORED
* @see ZipFileInterface::METHOD_DEFLATED * @see ZipFileInterface::METHOD_DEFLATED
* @see ZipFileInterface::METHOD_BZIP2 * @see ZipFileInterface::METHOD_BZIP2
@@ -330,7 +311,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
*/ */
public function addFilesFromGlob($inputDir, $globPattern, $localPath = '/', $compressionMethod = null); public function addFilesFromGlob($inputDir, $globPattern, $localPath = '/', $compressionMethod = null);
@@ -345,7 +325,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2. * Use ZipFile::METHOD_STORED, ZipFile::METHOD_DEFLATED or ZipFile::METHOD_BZIP2.
* If null, then auto choosing method. * If null, then auto choosing method.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
*/ */
public function addFilesFromGlobRecursive($inputDir, $globPattern, $localPath = '/', $compressionMethod = null); public function addFilesFromGlobRecursive($inputDir, $globPattern, $localPath = '/', $compressionMethod = null);
@@ -393,8 +372,7 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* @param string $oldName Old entry name. * @param string $oldName Old entry name.
* @param string $newName New entry name. * @param string $newName New entry name.
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException * @throws ZipEntryNotFoundException
* @throws ZipNotFoundEntry
*/ */
public function rename($oldName, $newName); public function rename($oldName, $newName);
@@ -403,7 +381,7 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $entryName Zip Entry name. * @param string $entryName Zip Entry name.
* @return ZipFileInterface * @return ZipFileInterface
* @throws ZipNotFoundEntry If entry not found. * @throws ZipEntryNotFoundException If entry not found.
*/ */
public function deleteFromName($entryName); public function deleteFromName($entryName);
@@ -412,7 +390,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $globPattern Glob pattern * @param string $globPattern Glob pattern
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax * @sse https://en.wikipedia.org/wiki/Glob_(programming) Glob pattern syntax
*/ */
public function deleteFromGlob($globPattern); public function deleteFromGlob($globPattern);
@@ -422,7 +399,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $regexPattern Regex pattern * @param string $regexPattern Regex pattern
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
*/ */
public function deleteFromRegex($regexPattern); public function deleteFromRegex($regexPattern);
@@ -576,7 +552,6 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* *
* @param string $filename Output filename * @param string $filename Output filename
* @return ZipFileInterface * @return ZipFileInterface
* @throws InvalidArgumentException
* @throws ZipException * @throws ZipException
*/ */
public function saveAsFile($filename); public function saveAsFile($filename);
@@ -608,14 +583,12 @@ interface ZipFileInterface extends \Countable, \ArrayAccess, \Iterator
* @param string|null $mimeType Mime-Type * @param string|null $mimeType Mime-Type
* @param bool $attachment Http Header 'Content-Disposition' if true then attachment otherwise inline * @param bool $attachment Http Header 'Content-Disposition' if true then attachment otherwise inline
* @return ResponseInterface * @return ResponseInterface
* @throws InvalidArgumentException
*/ */
public function outputAsResponse(ResponseInterface $response, $outputFilename, $mimeType = null, $attachment = true); public function outputAsResponse(ResponseInterface $response, $outputFilename, $mimeType = null, $attachment = true);
/** /**
* Returns the zip archive as a string. * Returns the zip archive as a string.
* @return string * @return string
* @throws InvalidArgumentException
*/ */
public function outputAsString(); public function outputAsString();

View File

@@ -2,7 +2,7 @@
namespace PhpZip; namespace PhpZip;
use PhpZip\Exception\ZipAuthenticationException; use PhpZip\Exception\ZipException;
/** /**
* Some tests from the official extension of php-zip. * Some tests from the official extension of php-zip.
@@ -12,6 +12,7 @@ class PhpZipExtResourceTest extends ZipTestCase
/** /**
* Bug #7214 (zip_entry_read() binary safe) * Bug #7214 (zip_entry_read() binary safe)
* @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug7214.phpt * @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug7214.phpt
* @throws ZipException
*/ */
public function testBinaryNull() public function testBinaryNull()
{ {
@@ -21,16 +22,17 @@ class PhpZipExtResourceTest extends ZipTestCase
$zipFile->openFile($filename); $zipFile->openFile($filename);
foreach ($zipFile as $name => $contents) { foreach ($zipFile as $name => $contents) {
$info = $zipFile->getEntryInfo($name); $info = $zipFile->getEntryInfo($name);
self::assertEquals(strlen($contents), $info->getSize()); $this->assertEquals(strlen($contents), $info->getSize());
} }
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($filename); $this->assertCorrectZipArchive($filename);
} }
/** /**
* Bug #8009 (cannot add again same entry to an archive) * Bug #8009 (cannot add again same entry to an archive)
* @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug8009.phpt * @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug8009.phpt
* @throws ZipException
*/ */
public function testBug8009() public function testBug8009()
{ {
@@ -42,13 +44,13 @@ class PhpZipExtResourceTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertCount(2, $zipFile); $this->assertCount(2, $zipFile);
self::assertTrue(isset($zipFile['1.txt'])); $this->assertTrue(isset($zipFile['1.txt']));
self::assertTrue(isset($zipFile['2.txt'])); $this->assertTrue(isset($zipFile['2.txt']));
self::assertEquals($zipFile['2.txt'], $zipFile['1.txt']); $this->assertEquals($zipFile['2.txt'], $zipFile['1.txt']);
$zipFile->close(); $zipFile->close();
} }
@@ -58,17 +60,18 @@ class PhpZipExtResourceTest extends ZipTestCase
* @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug40228-mb.phpt * @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug40228-mb.phpt
* @dataProvider provideBug40228 * @dataProvider provideBug40228
* @param string $filename * @param string $filename
* @throws ZipException
*/ */
public function testBug40228($filename) public function testBug40228($filename)
{ {
self::assertTrue(mkdir($this->outputDirname, 0755, true)); $this->assertTrue(mkdir($this->outputDirname, 0755, true));
$zipFile = new ZipFile(); $zipFile = new ZipFile();
$zipFile->openFile($filename); $zipFile->openFile($filename);
$zipFile->extractTo($this->outputDirname); $zipFile->extractTo($this->outputDirname);
$zipFile->close(); $zipFile->close();
self::assertTrue(is_dir($this->outputDirname . '/test/empty')); $this->assertTrue(is_dir($this->outputDirname . '/test/empty'));
} }
public function provideBug40228() public function provideBug40228()
@@ -83,6 +86,7 @@ class PhpZipExtResourceTest extends ZipTestCase
* @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug49072.phpt * @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug49072.phpt
* @expectedException \PhpZip\Exception\Crc32Exception * @expectedException \PhpZip\Exception\Crc32Exception
* @expectedExceptionMessage file1 * @expectedExceptionMessage file1
* @throws ZipException
*/ */
public function testBug49072() public function testBug49072()
{ {
@@ -98,21 +102,22 @@ class PhpZipExtResourceTest extends ZipTestCase
* @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug70752.phpt * @see https://github.com/php/php-src/blob/master/ext/zip/tests/bug70752.phpt
* @expectedException \PhpZip\Exception\ZipAuthenticationException * @expectedException \PhpZip\Exception\ZipAuthenticationException
* @expectedExceptionMessage Bad password for entry bug70752.txt * @expectedExceptionMessage Bad password for entry bug70752.txt
* @throws ZipException
*/ */
public function testBug70752() public function testBug70752()
{ {
$filename = __DIR__ . '/php-zip-ext-test-resources/bug70752.zip'; $filename = __DIR__ . '/php-zip-ext-test-resources/bug70752.zip';
self::assertTrue(mkdir($this->outputDirname, 0755, true)); $this->assertTrue(mkdir($this->outputDirname, 0755, true));
$zipFile = new ZipFile(); $zipFile = new ZipFile();
try { try {
$zipFile->openFile($filename); $zipFile->openFile($filename);
$zipFile->setReadPassword('bar'); $zipFile->setReadPassword('bar');
$zipFile->extractTo($this->outputDirname); $zipFile->extractTo($this->outputDirname);
self::markTestIncomplete('failed test'); $this->markTestIncomplete('failed test');
} catch (ZipAuthenticationException $exception) { } catch (ZipException $exception) {
self::assertFalse(file_exists($this->outputDirname . '/bug70752.txt')); $this->assertFalse(file_exists($this->outputDirname . '/bug70752.txt'));
$zipFile->close(); $zipFile->close();
throw $exception; throw $exception;
} }
@@ -121,6 +126,7 @@ class PhpZipExtResourceTest extends ZipTestCase
/** /**
* Bug #12414 ( extracting files from damaged archives) * Bug #12414 ( extracting files from damaged archives)
* @see https://github.com/php/php-src/blob/master/ext/zip/tests/pecl12414.phpt * @see https://github.com/php/php-src/blob/master/ext/zip/tests/pecl12414.phpt
* @throws ZipException
*/ */
public function testPecl12414() public function testPecl12414()
{ {
@@ -132,10 +138,10 @@ class PhpZipExtResourceTest extends ZipTestCase
$zipFile->openFile($filename); $zipFile->openFile($filename);
$info = $zipFile->getEntryInfo($entryName); $info = $zipFile->getEntryInfo($entryName);
self::assertTrue($info->getSize() > 0); $this->assertTrue($info->getSize() > 0);
$contents = $zipFile[$entryName]; $contents = $zipFile[$entryName];
self::assertEquals(strlen($contents), $info->getSize()); $this->assertEquals(strlen($contents), $info->getSize());
$zipFile->close(); $zipFile->close();
} }

View File

@@ -2,6 +2,7 @@
namespace PhpZip; namespace PhpZip;
use PhpZip\Exception\ZipException;
use PhpZip\Util\CryptoUtil; use PhpZip\Util\CryptoUtil;
/** /**
@@ -9,14 +10,17 @@ use PhpZip\Util\CryptoUtil;
*/ */
class ZipAlignTest extends ZipTestCase class ZipAlignTest extends ZipTestCase
{ {
/**
* @throws ZipException
*/
public function testApkAlignedAndSetZipAlignAndReSave() public function testApkAlignedAndSetZipAlignAndReSave()
{ {
$filename = __DIR__ . '/resources/test.apk'; $filename = __DIR__ . '/resources/test.apk';
self::assertCorrectZipArchive($filename); $this->assertCorrectZipArchive($filename);
$result = self::doZipAlignVerify($filename); $result = $this->assertVerifyZipAlign($filename);
if (null !== $result) { if (null !== $result) {
self::assertTrue($result); $this->assertTrue($result);
} }
$zipFile = new ZipFile(); $zipFile = new ZipFile();
@@ -25,15 +29,16 @@ class ZipAlignTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$result = self::doZipAlignVerify($this->outputFilename, true); $result = $this->assertVerifyZipAlign($this->outputFilename, true);
if (null !== $result) { if (null !== $result) {
self::assertTrue($result); $this->assertTrue($result);
} }
} }
/** /**
* Test zip alignment. * Test zip alignment.
* @throws ZipException
*/ */
public function testZipAlignSourceZip() public function testZipAlignSourceZip()
{ {
@@ -48,30 +53,33 @@ class ZipAlignTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$result = self::doZipAlignVerify($this->outputFilename); $result = $this->assertVerifyZipAlign($this->outputFilename);
if ($result === null) { if ($result === null) {
return; return;
} // zip align not installed } // zip align not installed
// check not zip align // check not zip align
self::assertFalse($result); $this->assertFalse($result);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
$zipFile->setZipAlign(4); $zipFile->setZipAlign(4);
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$result = self::doZipAlignVerify($this->outputFilename, true); $result = $this->assertVerifyZipAlign($this->outputFilename, true);
self::assertNotNull($result); $this->assertNotNull($result);
// check zip align // check zip align
self::assertTrue($result); $this->assertTrue($result);
} }
/**
* @throws ZipException
*/
public function testZipAlignNewFiles() public function testZipAlignNewFiles()
{ {
$zipFile = new ZipFile(); $zipFile = new ZipFile();
@@ -86,16 +94,19 @@ class ZipAlignTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$result = self::doZipAlignVerify($this->outputFilename); $result = $this->assertVerifyZipAlign($this->outputFilename);
if ($result === null) { if ($result === null) {
return; return;
} // zip align not installed } // zip align not installed
// check not zip align // check not zip align
self::assertTrue($result); $this->assertTrue($result);
} }
/**
* @throws ZipException
*/
public function testZipAlignFromModifiedZipArchive() public function testZipAlignFromModifiedZipArchive()
{ {
$zipFile = new ZipFile(); $zipFile = new ZipFile();
@@ -109,15 +120,15 @@ class ZipAlignTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$result = self::doZipAlignVerify($this->outputFilename); $result = $this->assertVerifyZipAlign($this->outputFilename);
if ($result === null) { if ($result === null) {
return; return;
} // zip align not installed } // zip align not installed
// check not zip align // check not zip align
self::assertFalse($result); $this->assertFalse($result);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
$zipFile->deleteFromRegex("~entry2[\d]+\.txt$~s"); $zipFile->deleteFromRegex("~entry2[\d]+\.txt$~s");
@@ -136,12 +147,12 @@ class ZipAlignTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$result = self::doZipAlignVerify($this->outputFilename, true); $result = $this->assertVerifyZipAlign($this->outputFilename, true);
self::assertNotNull($result); $this->assertNotNull($result);
// check zip align // check zip align
self::assertTrue($result); $this->assertTrue($result);
} }
} }

View File

@@ -2,6 +2,8 @@
namespace PhpZip; namespace PhpZip;
use PhpZip\Exception\ZipException;
class ZipFileExtended extends ZipFile class ZipFileExtended extends ZipFile
{ {
protected function onBeforeSave() protected function onBeforeSave()
@@ -14,29 +16,32 @@ class ZipFileExtended extends ZipFile
class ZipEventTest extends ZipTestCase class ZipEventTest extends ZipTestCase
{ {
/**
* @throws ZipException
*/
public function testBeforeSave() public function testBeforeSave()
{ {
$zipFile = new ZipFileExtended(); $zipFile = new ZipFileExtended();
$zipFile->openFile(__DIR__ . '/resources/test.apk'); $zipFile->openFile(__DIR__ . '/resources/test.apk');
self::assertTrue(isset($zipFile['META-INF/MANIFEST.MF'])); $this->assertTrue(isset($zipFile['META-INF/MANIFEST.MF']));
self::assertTrue(isset($zipFile['META-INF/CERT.SF'])); $this->assertTrue(isset($zipFile['META-INF/CERT.SF']));
self::assertTrue(isset($zipFile['META-INF/CERT.RSA'])); $this->assertTrue(isset($zipFile['META-INF/CERT.RSA']));
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
self::assertFalse(isset($zipFile['META-INF/MANIFEST.MF'])); $this->assertFalse(isset($zipFile['META-INF/MANIFEST.MF']));
self::assertFalse(isset($zipFile['META-INF/CERT.SF'])); $this->assertFalse(isset($zipFile['META-INF/CERT.SF']));
self::assertFalse(isset($zipFile['META-INF/CERT.RSA'])); $this->assertFalse(isset($zipFile['META-INF/CERT.RSA']));
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$result = self::doZipAlignVerify($this->outputFilename); $result = $this->assertVerifyZipAlign($this->outputFilename);
if (null !== $result) { if (null !== $result) {
self::assertTrue($result); $this->assertTrue($result);
} }
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFalse(isset($zipFile['META-INF/MANIFEST.MF'])); $this->assertFalse(isset($zipFile['META-INF/MANIFEST.MF']));
self::assertFalse(isset($zipFile['META-INF/CERT.SF'])); $this->assertFalse(isset($zipFile['META-INF/CERT.SF']));
self::assertFalse(isset($zipFile['META-INF/CERT.RSA'])); $this->assertFalse(isset($zipFile['META-INF/CERT.RSA']));
$zipFile->close(); $zipFile->close();
} }
} }

View File

@@ -2,6 +2,7 @@
namespace PhpZip; namespace PhpZip;
use PhpZip\Exception\ZipException;
use PhpZip\Util\Iterator\IgnoreFilesFilterIterator; use PhpZip\Util\Iterator\IgnoreFilesFilterIterator;
use PhpZip\Util\Iterator\IgnoreFilesRecursiveFilterIterator; use PhpZip\Util\Iterator\IgnoreFilesRecursiveFilterIterator;
@@ -72,6 +73,9 @@ class ZipFileAddDirTest extends ZipTestCase
self::assertEmpty($actualResultFiles); self::assertEmpty($actualResultFiles);
} }
/**
* @throws ZipException
*/
public function testAddDirWithLocalPath() public function testAddDirWithLocalPath()
{ {
$localPath = 'to/path'; $localPath = 'to/path';
@@ -81,10 +85,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'.hidden', '.hidden',
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
@@ -93,6 +97,9 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testAddDirWithoutLocalPath() public function testAddDirWithoutLocalPath()
{ {
$zipFile = new ZipFile(); $zipFile = new ZipFile();
@@ -100,10 +107,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'.hidden', '.hidden',
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
@@ -112,6 +119,9 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testAddFilesFromIterator() public function testAddFilesFromIterator()
{ {
$localPath = 'to/project'; $localPath = 'to/project';
@@ -123,10 +133,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'.hidden', '.hidden',
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
@@ -135,6 +145,9 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testAddFilesFromIteratorEmptyLocalPath() public function testAddFilesFromIteratorEmptyLocalPath()
{ {
$localPath = ''; $localPath = '';
@@ -146,10 +159,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'.hidden', '.hidden',
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
@@ -158,6 +171,9 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testAddFilesFromRecursiveIterator() public function testAddFilesFromRecursiveIterator()
{ {
$localPath = 'to/project'; $localPath = 'to/project';
@@ -169,13 +185,16 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, array_keys(self::$files), $localPath); $this->assertFilesResult($zipFile, array_keys(self::$files), $localPath);
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testAddRecursiveDirWithLocalPath() public function testAddRecursiveDirWithLocalPath()
{ {
$localPath = 'to/path'; $localPath = 'to/path';
@@ -185,13 +204,16 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, array_keys(self::$files), $localPath); $this->assertFilesResult($zipFile, array_keys(self::$files), $localPath);
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testAddRecursiveDirWithoutLocalPath() public function testAddRecursiveDirWithoutLocalPath()
{ {
$zipFile = new ZipFile(); $zipFile = new ZipFile();
@@ -199,13 +221,16 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, array_keys(self::$files)); $this->assertFilesResult($zipFile, array_keys(self::$files));
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testAddFilesFromIteratorWithIgnoreFiles() public function testAddFilesFromIteratorWithIgnoreFiles()
{ {
$localPath = 'to/project'; $localPath = 'to/project';
@@ -222,16 +247,19 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'.hidden', '.hidden',
'text file.txt', 'text file.txt',
], $localPath); ], $localPath);
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testAddFilesFromRecursiveIteratorWithIgnoreFiles() public function testAddFilesFromRecursiveIteratorWithIgnoreFiles()
{ {
$localPath = 'to/project'; $localPath = 'to/project';
@@ -250,10 +278,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
'empty dir/', 'empty dir/',
@@ -268,6 +296,7 @@ class ZipFileAddDirTest extends ZipTestCase
/** /**
* Create archive and add files from glob pattern * Create archive and add files from glob pattern
* @throws ZipException
*/ */
public function testAddFilesFromGlob() public function testAddFilesFromGlob()
{ {
@@ -278,10 +307,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
], $localPath); ], $localPath);
@@ -290,6 +319,7 @@ class ZipFileAddDirTest extends ZipTestCase
/** /**
* Create archive and add recursively files from glob pattern * Create archive and add recursively files from glob pattern
* @throws ZipException
*/ */
public function testAddFilesFromGlobRecursive() public function testAddFilesFromGlobRecursive()
{ {
@@ -300,10 +330,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
'category/list.txt', 'category/list.txt',
@@ -317,6 +347,7 @@ class ZipFileAddDirTest extends ZipTestCase
/** /**
* Create archive and add files from regex pattern * Create archive and add files from regex pattern
* @throws ZipException
*/ */
public function testAddFilesFromRegex() public function testAddFilesFromRegex()
{ {
@@ -327,10 +358,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
], $localPath); ], $localPath);
@@ -339,6 +370,7 @@ class ZipFileAddDirTest extends ZipTestCase
/** /**
* Create archive and add files recursively from regex pattern * Create archive and add files recursively from regex pattern
* @throws ZipException
*/ */
public function testAddFilesFromRegexRecursive() public function testAddFilesFromRegexRecursive()
{ {
@@ -349,10 +381,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, [ $this->assertFilesResult($zipFile, [
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
'category/list.txt', 'category/list.txt',
@@ -364,6 +396,9 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testArrayAccessAddDir() public function testArrayAccessAddDir()
{ {
$localPath = 'path/to'; $localPath = 'path/to';
@@ -374,10 +409,10 @@ class ZipFileAddDirTest extends ZipTestCase
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertFilesResult($zipFile, array_keys(self::$files), $localPath); $this->assertFilesResult($zipFile, array_keys(self::$files), $localPath);
$zipFile->close(); $zipFile->close();
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,7 @@ class ZipMatcherTest extends \PHPUnit_Framework_TestCase
} }
$matcher = $zipFile->matcher(); $matcher = $zipFile->matcher();
self::assertInstanceOf(ZipEntryMatcher::class, $matcher); $this->assertInstanceOf(ZipEntryMatcher::class, $matcher);
$this->assertTrue(is_array($matcher->getMatches())); $this->assertTrue(is_array($matcher->getMatches()));
$this->assertCount(0, $matcher); $this->assertCount(0, $matcher);
@@ -40,7 +40,7 @@ class ZipMatcherTest extends \PHPUnit_Framework_TestCase
$matcher->setPassword('qwerty'); $matcher->setPassword('qwerty');
$info = $zipFile->getAllInfo(); $info = $zipFile->getAllInfo();
array_walk($info, function (ZipInfo $zipInfo) use ($actualMatches) { array_walk($info, function (ZipInfo $zipInfo) use ($actualMatches) {
self::assertEquals($zipInfo->isEncrypted(), in_array($zipInfo->getName(), $actualMatches)); $this->assertEquals($zipInfo->isEncrypted(), in_array($zipInfo->getName(), $actualMatches));
}); });
$matcher->all(); $matcher->all();
@@ -86,12 +86,12 @@ class ZipMatcherTest extends \PHPUnit_Framework_TestCase
]; ];
foreach ($renameEntriesArray as $name) { foreach ($renameEntriesArray as $name) {
self::assertTrue(isset($zipFile[$name])); $this->assertTrue(isset($zipFile[$name]));
} }
$matcher = $zipFile->matcher(); $matcher = $zipFile->matcher();
$matcher->match('~^file_(1|5)\d+~'); $matcher->match('~^file_(1|5)\d+~');
self::assertEquals($matcher->getMatches(), $renameEntriesArray); $this->assertEquals($matcher->getMatches(), $renameEntriesArray);
$matcher->invoke(function ($entryName) use ($zipFile) { $matcher->invoke(function ($entryName) use ($zipFile) {
$newName = preg_replace('~\.(jpe?g)$~i', '.no_optimize.$1', $entryName); $newName = preg_replace('~\.(jpe?g)$~i', '.no_optimize.$1', $entryName);
@@ -99,11 +99,11 @@ class ZipMatcherTest extends \PHPUnit_Framework_TestCase
}); });
foreach ($renameEntriesArray as $name) { foreach ($renameEntriesArray as $name) {
self::assertFalse(isset($zipFile[$name])); $this->assertFalse(isset($zipFile[$name]));
$pathInfo = pathinfo($name); $pathInfo = pathinfo($name);
$newName = $pathInfo['filename'].'.no_optimize.'.$pathInfo['extension']; $newName = $pathInfo['filename'].'.no_optimize.'.$pathInfo['extension'];
self::assertTrue(isset($zipFile[$newName])); $this->assertTrue(isset($zipFile[$newName]));
} }
$zipFile->close(); $zipFile->close();

View File

@@ -3,6 +3,8 @@
namespace PhpZip; namespace PhpZip;
use PhpZip\Exception\ZipAuthenticationException; use PhpZip\Exception\ZipAuthenticationException;
use PhpZip\Exception\ZipEntryNotFoundException;
use PhpZip\Exception\ZipException;
use PhpZip\Model\ZipInfo; use PhpZip\Model\ZipInfo;
use PhpZip\Util\CryptoUtil; use PhpZip\Util\CryptoUtil;
@@ -13,6 +15,7 @@ class ZipPasswordTest extends ZipFileAddDirTest
{ {
/** /**
* Test archive password. * Test archive password.
* @throws ZipException
*/ */
public function testSetPassword() public function testSetPassword()
{ {
@@ -30,7 +33,7 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename, $password); $this->assertCorrectZipArchive($this->outputFilename, $password);
// check bad password for ZipCrypto // check bad password for ZipCrypto
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
@@ -38,20 +41,20 @@ class ZipPasswordTest extends ZipFileAddDirTest
foreach ($zipFile->getListFiles() as $entryName) { foreach ($zipFile->getListFiles() as $entryName) {
try { try {
$zipFile[$entryName]; $zipFile[$entryName];
self::fail("Expected Exception has not been raised."); $this->fail("Expected Exception has not been raised.");
} catch (ZipAuthenticationException $ae) { } catch (ZipAuthenticationException $ae) {
self::assertNotNull($ae); $this->assertNotNull($ae);
} }
} }
// check correct password for ZipCrypto // check correct password for ZipCrypto
$zipFile->setReadPassword($password); $zipFile->setReadPassword($password);
foreach ($zipFile->getAllInfo() as $info) { foreach ($zipFile->getAllInfo() as $info) {
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertContains('ZipCrypto', $info->getMethodName()); $this->assertContains('ZipCrypto', $info->getMethodName());
$decryptContent = $zipFile[$info->getName()]; $decryptContent = $zipFile[$info->getName()];
self::assertNotEmpty($decryptContent); $this->assertNotEmpty($decryptContent);
self::assertContains('<?php', $decryptContent); $this->assertContains('<?php', $decryptContent);
} }
// change encryption method to WinZip Aes and update file // change encryption method to WinZip Aes and update file
@@ -59,7 +62,7 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename, $password); $this->assertCorrectZipArchive($this->outputFilename, $password);
// check from WinZip AES encryption // check from WinZip AES encryption
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
@@ -68,20 +71,20 @@ class ZipPasswordTest extends ZipFileAddDirTest
foreach ($zipFile->getListFiles() as $entryName) { foreach ($zipFile->getListFiles() as $entryName) {
try { try {
$zipFile[$entryName]; $zipFile[$entryName];
self::fail("Expected Exception has not been raised."); $this->fail("Expected Exception has not been raised.");
} catch (ZipAuthenticationException $ae) { } catch (ZipAuthenticationException $ae) {
self::assertNotNull($ae); $this->assertNotNull($ae);
} }
} }
// set correct password WinZip AES // set correct password WinZip AES
$zipFile->setReadPassword($password); $zipFile->setReadPassword($password);
foreach ($zipFile->getAllInfo() as $info) { foreach ($zipFile->getAllInfo() as $info) {
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertContains('WinZip', $info->getMethodName()); $this->assertContains('WinZip', $info->getMethodName());
$decryptContent = $zipFile[$info->getName()]; $decryptContent = $zipFile[$info->getName()];
self::assertNotEmpty($decryptContent); $this->assertNotEmpty($decryptContent);
self::assertContains('<?php', $decryptContent); $this->assertContains('<?php', $decryptContent);
} }
// clear password // clear password
@@ -91,16 +94,19 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename); $this->assertCorrectZipArchive($this->outputFilename);
// check remove password // check remove password
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
foreach ($zipFile->getAllInfo() as $info) { foreach ($zipFile->getAllInfo() as $info) {
self::assertFalse($info->isEncrypted()); $this->assertFalse($info->isEncrypted());
} }
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipException
*/
public function testTraditionalEncryption() public function testTraditionalEncryption()
{ {
if (PHP_INT_SIZE === 4) { if (PHP_INT_SIZE === 4) {
@@ -115,15 +121,15 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zip->saveAsFile($this->outputFilename); $zip->saveAsFile($this->outputFilename);
$zip->close(); $zip->close();
self::assertCorrectZipArchive($this->outputFilename, $password); $this->assertCorrectZipArchive($this->outputFilename, $password);
$zip->openFile($this->outputFilename); $zip->openFile($this->outputFilename);
$zip->setReadPassword($password); $zip->setReadPassword($password);
self::assertFilesResult($zip, array_keys(self::$files)); $this->assertFilesResult($zip, array_keys(self::$files));
foreach ($zip->getAllInfo() as $info) { foreach ($zip->getAllInfo() as $info) {
if (!$info->isFolder()) { if (!$info->isFolder()) {
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertContains('ZipCrypto', $info->getMethodName()); $this->assertContains('ZipCrypto', $info->getMethodName());
} }
} }
$zip->close(); $zip->close();
@@ -133,6 +139,7 @@ class ZipPasswordTest extends ZipFileAddDirTest
* @dataProvider winZipKeyStrengthProvider * @dataProvider winZipKeyStrengthProvider
* @param int $encryptionMethod * @param int $encryptionMethod
* @param int $bitSize * @param int $bitSize
* @throws ZipException
*/ */
public function testWinZipAesEncryption($encryptionMethod, $bitSize) public function testWinZipAesEncryption($encryptionMethod, $bitSize)
{ {
@@ -144,16 +151,16 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zip->saveAsFile($this->outputFilename); $zip->saveAsFile($this->outputFilename);
$zip->close(); $zip->close();
self::assertCorrectZipArchive($this->outputFilename, $password); $this->assertCorrectZipArchive($this->outputFilename, $password);
$zip->openFile($this->outputFilename); $zip->openFile($this->outputFilename);
$zip->setReadPassword($password); $zip->setReadPassword($password);
self::assertFilesResult($zip, array_keys(self::$files)); $this->assertFilesResult($zip, array_keys(self::$files));
foreach ($zip->getAllInfo() as $info) { foreach ($zip->getAllInfo() as $info) {
if (!$info->isFolder()) { if (!$info->isFolder()) {
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertEquals($info->getEncryptionMethod(), $encryptionMethod); $this->assertEquals($info->getEncryptionMethod(), $encryptionMethod);
self::assertContains('WinZip AES-' . $bitSize, $info->getMethodName()); $this->assertContains('WinZip AES-' . $bitSize, $info->getMethodName());
} }
} }
$zip->close(); $zip->close();
@@ -172,6 +179,10 @@ class ZipPasswordTest extends ZipFileAddDirTest
]; ];
} }
/**
* @throws Exception\ZipEntryNotFoundException
* @throws ZipException
*/
public function testEncryptionEntries() public function testEncryptionEntries()
{ {
if (PHP_INT_SIZE === 4) { if (PHP_INT_SIZE === 4) {
@@ -191,7 +202,7 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zip->openFile($this->outputFilename); $zip->openFile($this->outputFilename);
$zip->setReadPasswordEntry('.hidden', $password1); $zip->setReadPasswordEntry('.hidden', $password1);
$zip->setReadPasswordEntry('text file.txt', $password2); $zip->setReadPasswordEntry('text file.txt', $password2);
self::assertFilesResult($zip, [ $this->assertFilesResult($zip, [
'.hidden', '.hidden',
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
@@ -199,19 +210,23 @@ class ZipPasswordTest extends ZipFileAddDirTest
]); ]);
$info = $zip->getEntryInfo('.hidden'); $info = $zip->getEntryInfo('.hidden');
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertContains('ZipCrypto', $info->getMethodName()); $this->assertContains('ZipCrypto', $info->getMethodName());
$info = $zip->getEntryInfo('text file.txt'); $info = $zip->getEntryInfo('text file.txt');
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertContains('WinZip AES', $info->getMethodName()); $this->assertContains('WinZip AES', $info->getMethodName());
self::assertFalse($zip->getEntryInfo('Текстовый документ.txt')->isEncrypted()); $this->assertFalse($zip->getEntryInfo('Текстовый документ.txt')->isEncrypted());
self::assertFalse($zip->getEntryInfo('empty dir/')->isEncrypted()); $this->assertFalse($zip->getEntryInfo('empty dir/')->isEncrypted());
$zip->close(); $zip->close();
} }
/**
* @throws Exception\ZipEntryNotFoundException
* @throws ZipException
*/
public function testEncryptionEntriesWithDefaultPassword() public function testEncryptionEntriesWithDefaultPassword()
{ {
if (PHP_INT_SIZE === 4) { if (PHP_INT_SIZE === 4) {
@@ -234,7 +249,7 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zip->setReadPassword($defaultPassword); $zip->setReadPassword($defaultPassword);
$zip->setReadPasswordEntry('.hidden', $password1); $zip->setReadPasswordEntry('.hidden', $password1);
$zip->setReadPasswordEntry('text file.txt', $password2); $zip->setReadPasswordEntry('text file.txt', $password2);
self::assertFilesResult($zip, [ $this->assertFilesResult($zip, [
'.hidden', '.hidden',
'text file.txt', 'text file.txt',
'Текстовый документ.txt', 'Текстовый документ.txt',
@@ -242,18 +257,18 @@ class ZipPasswordTest extends ZipFileAddDirTest
]); ]);
$info = $zip->getEntryInfo('.hidden'); $info = $zip->getEntryInfo('.hidden');
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertContains('ZipCrypto', $info->getMethodName()); $this->assertContains('ZipCrypto', $info->getMethodName());
$info = $zip->getEntryInfo('text file.txt'); $info = $zip->getEntryInfo('text file.txt');
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertContains('WinZip AES', $info->getMethodName()); $this->assertContains('WinZip AES', $info->getMethodName());
$info = $zip->getEntryInfo('Текстовый документ.txt'); $info = $zip->getEntryInfo('Текстовый документ.txt');
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
self::assertContains('WinZip AES', $info->getMethodName()); $this->assertContains('WinZip AES', $info->getMethodName());
self::assertFalse($zip->getEntryInfo('empty dir/')->isEncrypted()); $this->assertFalse($zip->getEntryInfo('empty dir/')->isEncrypted());
$zip->close(); $zip->close();
} }
@@ -271,28 +286,32 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zipFile->outputAsString(); $zipFile->outputAsString();
} }
/**
* @throws Exception\ZipEntryNotFoundException
* @throws ZipException
*/
public function testEntryPassword() public function testEntryPassword()
{ {
$zipFile = new ZipFile(); $zipFile = new ZipFile();
$zipFile->setPassword('pass'); $zipFile->setPassword('pass');
$zipFile['file'] = 'content'; $zipFile['file'] = 'content';
self::assertFalse($zipFile->getEntryInfo('file')->isEncrypted()); $this->assertFalse($zipFile->getEntryInfo('file')->isEncrypted());
for ($i = 1; $i <= 10; $i++) { for ($i = 1; $i <= 10; $i++) {
$zipFile['file' . $i] = 'content'; $zipFile['file' . $i] = 'content';
if ($i < 6) { if ($i < 6) {
$zipFile->setPasswordEntry('file' . $i, 'pass'); $zipFile->setPasswordEntry('file' . $i, 'pass');
self::assertTrue($zipFile->getEntryInfo('file' . $i)->isEncrypted()); $this->assertTrue($zipFile->getEntryInfo('file' . $i)->isEncrypted());
} else { } else {
self::assertFalse($zipFile->getEntryInfo('file' . $i)->isEncrypted()); $this->assertFalse($zipFile->getEntryInfo('file' . $i)->isEncrypted());
} }
} }
$zipFile->disableEncryptionEntry('file3'); $zipFile->disableEncryptionEntry('file3');
self::assertFalse($zipFile->getEntryInfo('file3')->isEncrypted()); $this->assertFalse($zipFile->getEntryInfo('file3')->isEncrypted());
self::asserttrue($zipFile->getEntryInfo('file2')->isEncrypted()); $this->asserttrue($zipFile->getEntryInfo('file2')->isEncrypted());
$zipFile->disableEncryption(); $zipFile->disableEncryption();
$infoList = $zipFile->getAllInfo(); $infoList = $zipFile->getAllInfo();
array_walk($infoList, function (ZipInfo $zipInfo) { array_walk($infoList, function (ZipInfo $zipInfo) {
self::assertFalse($zipInfo->isEncrypted()); $this->assertFalse($zipInfo->isEncrypted());
}); });
$zipFile->close(); $zipFile->close();
} }
@@ -308,6 +327,10 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zipFile->setPasswordEntry('file', 'pass', 99); $zipFile->setPasswordEntry('file', 'pass', 99);
} }
/**
* @throws ZipEntryNotFoundException
* @throws ZipException
*/
public function testArchivePasswordUpdateWithoutSetReadPassword() public function testArchivePasswordUpdateWithoutSetReadPassword()
{ {
$zipFile = new ZipFile(); $zipFile = new ZipFile();
@@ -318,37 +341,38 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zipFile->saveAsFile($this->outputFilename); $zipFile->saveAsFile($this->outputFilename);
$zipFile->close(); $zipFile->close();
self::assertCorrectZipArchive($this->outputFilename, 'password'); $this->assertCorrectZipArchive($this->outputFilename, 'password');
$zipFile->openFile($this->outputFilename); $zipFile->openFile($this->outputFilename);
self::assertCount(3, $zipFile); $this->assertCount(3, $zipFile);
foreach ($zipFile->getAllInfo() as $info) { foreach ($zipFile->getAllInfo() as $info) {
self::assertTrue($info->isEncrypted()); $this->assertTrue($info->isEncrypted());
} }
unset($zipFile['file3']); unset($zipFile['file3']);
$zipFile['file4'] = 'content'; $zipFile['file4'] = 'content';
$zipFile->rewrite(); $zipFile->rewrite();
self::assertCorrectZipArchive($this->outputFilename, 'password'); $this->assertCorrectZipArchive($this->outputFilename, 'password');
self::assertCount(3, $zipFile); $this->assertCount(3, $zipFile);
self::assertFalse(isset($zipFile['file3'])); $this->assertFalse(isset($zipFile['file3']));
self::assertTrue(isset($zipFile['file4'])); $this->assertTrue(isset($zipFile['file4']));
self::assertTrue($zipFile->getEntryInfo('file1')->isEncrypted()); $this->assertTrue($zipFile->getEntryInfo('file1')->isEncrypted());
self::assertTrue($zipFile->getEntryInfo('file2')->isEncrypted()); $this->assertTrue($zipFile->getEntryInfo('file2')->isEncrypted());
self::assertFalse($zipFile->getEntryInfo('file4')->isEncrypted()); $this->assertFalse($zipFile->getEntryInfo('file4')->isEncrypted());
self::assertEquals($zipFile['file4'], 'content'); $this->assertEquals($zipFile['file4'], 'content');
$zipFile->extractTo($this->outputDirname, ['file4']); $zipFile->extractTo($this->outputDirname, ['file4']);
self::assertTrue(file_exists($this->outputDirname . DIRECTORY_SEPARATOR . 'file4')); $this->assertTrue(file_exists($this->outputDirname . DIRECTORY_SEPARATOR . 'file4'));
self::assertEquals(file_get_contents($this->outputDirname . DIRECTORY_SEPARATOR . 'file4'), $zipFile['file4']); $this->assertEquals(file_get_contents($this->outputDirname . DIRECTORY_SEPARATOR . 'file4'), $zipFile['file4']);
$zipFile->close(); $zipFile->close();
} }
/** /**
* @see https://github.com/Ne-Lexa/php-zip/issues/9 * @see https://github.com/Ne-Lexa/php-zip/issues/9
* @throws ZipException
*/ */
public function testIssues9() public function testIssues9()
{ {
@@ -371,6 +395,10 @@ class ZipPasswordTest extends ZipFileAddDirTest
$zipFile->close(); $zipFile->close();
} }
/**
* @throws ZipEntryNotFoundException
* @throws ZipException
*/
public function testReadAesEncryptedAndRewriteArchive() public function testReadAesEncryptedAndRewriteArchive()
{ {
$file = __DIR__ . '/resources/aes_password_archive.zip'; $file = __DIR__ . '/resources/aes_password_archive.zip';

View File

@@ -79,7 +79,9 @@ class ZipTestCase extends \PHPUnit_Framework_TestCase
$command = "7z t -p" . escapeshellarg($password) . " " . escapeshellarg($filename); $command = "7z t -p" . escapeshellarg($password) . " " . escapeshellarg($filename);
exec($command, $output, $returnCode); exec($command, $output, $returnCode);
/**
* @var array $output
*/
$output = implode(PHP_EOL, $output); $output = implode(PHP_EOL, $output);
self::assertEquals($returnCode, 0); self::assertEquals($returnCode, 0);
@@ -121,7 +123,7 @@ class ZipTestCase extends \PHPUnit_Framework_TestCase
* @param bool $showErrors * @param bool $showErrors
* @return bool|null If null - can not install zipalign * @return bool|null If null - can not install zipalign
*/ */
public static function doZipAlignVerify($filename, $showErrors = false) public static function assertVerifyZipAlign($filename, $showErrors = false)
{ {
if (DIRECTORY_SEPARATOR !== '\\' && `which zipalign`) { if (DIRECTORY_SEPARATOR !== '\\' && `which zipalign`) {
exec("zipalign -c -v 4 " . escapeshellarg($filename), $output, $returnCode); exec("zipalign -c -v 4 " . escapeshellarg($filename), $output, $returnCode);