Add helper to cast to int|float, fix MemoryInfo on 32bits

Signed-off-by: Côme Chilliet <come.chilliet@nextcloud.com>
pull/36120/head
Côme Chilliet 3 years ago
parent 0f8c34cdc6
commit 94ecae4ade
No known key found for this signature in database
GPG Key ID: A3E2F658B28C760A
  1. 21
      lib/private/MemoryInfo.php
  2. 11
      lib/public/Util.php
  3. 4
      tests/lib/MemoryInfoTest.php

@ -24,8 +24,11 @@ declare(strict_types=1);
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC;
use OCP\Util;
/**
* Helper class that covers memory info.
*/
@ -45,14 +48,14 @@ class MemoryInfo {
/**
* Returns the php memory limit.
*
* @return int The memory limit in bytes.
* @return int|float The memory limit in bytes.
*/
public function getMemoryLimit(): int {
public function getMemoryLimit(): int|float {
$iniValue = trim(ini_get('memory_limit'));
if ($iniValue === '-1') {
return -1;
} elseif (is_numeric($iniValue) === true) {
return (int)$iniValue;
} elseif (is_numeric($iniValue)) {
return Util::numericToNumber($iniValue);
} else {
return $this->memoryLimitToBytes($iniValue);
}
@ -62,11 +65,15 @@ class MemoryInfo {
* Converts the ini memory limit to bytes.
*
* @param string $memoryLimit The "memory_limit" ini value
* @return int
*/
private function memoryLimitToBytes(string $memoryLimit): int {
private function memoryLimitToBytes(string $memoryLimit): int|float {
$last = strtolower(substr($memoryLimit, -1));
$memoryLimit = (int)substr($memoryLimit, 0, -1);
$number = substr($memoryLimit, 0, -1);
if (is_numeric($number)) {
$memoryLimit = Util::numericToNumber($number);
} else {
throw new \InvalidArgumentException($number.' is not a valid numeric string (in memory_limit ini directive)');
}
// intended fall through
switch ($last) {

@ -339,6 +339,17 @@ class Util {
return $user_part.'@localhost.localdomain';
}
/**
* Converts string to int of float depending if it fits an int
* @param numeric-string $number numeric string
* @return int|float int if it fits, float if it is too big
* @since 26.0.0
*/
public static function numericToNumber(string $number): int|float {
/* This is a hack to cast to (int|float) */
return 0 + $number;
}
/**
* Make a human file size (2048 to 2 kB)
* @param int $bytes file size in bytes

@ -71,10 +71,10 @@ class MemoryInfoTest extends TestCase {
* Tests that getMemoryLimit works as expected.
*
* @param string $iniValue The "memory_limit" ini data.
* @param int $expected The expected detected memory limit.
* @param int|float $expected The expected detected memory limit.
* @dataProvider getMemoryLimitTestData
*/
public function testMemoryLimit($iniValue, int $expected) {
public function testMemoryLimit(string $iniValue, int|float $expected) {
ini_set('memory_limit', $iniValue);
$memoryInfo = new MemoryInfo();
self::assertEquals($expected, $memoryInfo->getMemoryLimit());

Loading…
Cancel
Save