fix and test php_to_byte() related to #2756 #2556

This refactors the php_to_byte() method to properly return integers
always. A bug when reading byte sizes under 10 bytes was fixed. Infinity
(signaled by a -1 in php.ini) is now returned as -1.

According to [1] PHP supports size shortcuts for (K)ilobytes,
(M)egabytes and (G)igagbytes only. The support for Tera- and Petabytes
has been removed.

[1] https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
This commit is contained in:
Andreas Gohr 2019-04-24 14:10:54 +02:00
parent 7b564e1b69
commit a81f3d99fc
2 changed files with 48 additions and 21 deletions

View File

@ -0,0 +1,34 @@
<?php
class common_php_to_byte_test extends DokuWikiTest {
public function data() {
$data = [
['1G', 1073741824],
['8M', 8388608],
['8K', 8192],
['800', 800],
['8', 8],
['0', 0],
['-1', -1]
];
// larger sizes only work on 64bit platforms
if(PHP_INT_SIZE == 8) {
$data[] = ['8G', 8589934592];
}
return $data;
}
/**
* @dataProvider data
* @param string $value
* @param int $bytes
*/
public function test_undefined($value, $bytes) {
$this->assertSame($bytes, php_to_byte($value));
}
}

View File

@ -1640,34 +1640,27 @@ function unslash($string, $char = "'") {
/**
* Convert php.ini shorthands to byte
*
* @author <gilthans dot NO dot SPAM at gmail dot com>
* @link http://php.net/manual/en/ini.core.php#79564
* On 32 bit systems values >= 2GB will fail!
*
* @param string $v shorthands
* @return int|string
* -1 (infinite size) will be reported as -1
*
* @link https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
* @param string $value PHP size shorthand
* @return int
*/
function php_to_byte($v) {
$l = substr($v, -1);
$ret = substr($v, 0, -1);
switch(strtoupper($l)) {
/** @noinspection PhpMissingBreakStatementInspection */
case 'P':
$ret *= 1024;
/** @noinspection PhpMissingBreakStatementInspection */
case 'T':
$ret *= 1024;
/** @noinspection PhpMissingBreakStatementInspection */
function php_to_byte($value) {
switch (strtoupper($value[-1])) {
case 'G':
$ret *= 1024;
/** @noinspection PhpMissingBreakStatementInspection */
$ret = intval(substr($value, 0, -1)) * 1024 * 1024 * 1024;
break;
case 'M':
$ret *= 1024;
/** @noinspection PhpMissingBreakStatementInspection */
$ret = intval(substr($value, 0, -1)) * 1024 * 1024;
break;
case 'K':
$ret *= 1024;
$ret = intval(substr($value, 0, -1)) * 1024;
break;
default;
$ret *= 10;
$ret = intval($value);
break;
}
return $ret;