MemoryInfo.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC;
  8. use OCP\Util;
  9. /**
  10. * Helper class that covers memory info.
  11. */
  12. class MemoryInfo {
  13. public const RECOMMENDED_MEMORY_LIMIT = 512 * 1024 * 1024;
  14. /**
  15. * Tests if the memory limit is greater or equal the recommended value.
  16. *
  17. * @return bool
  18. */
  19. public function isMemoryLimitSufficient(): bool {
  20. $memoryLimit = $this->getMemoryLimit();
  21. return $memoryLimit === -1 || $memoryLimit >= self::RECOMMENDED_MEMORY_LIMIT;
  22. }
  23. /**
  24. * Returns the php memory limit.
  25. *
  26. * @return int|float The memory limit in bytes.
  27. */
  28. public function getMemoryLimit(): int|float {
  29. $iniValue = trim(ini_get('memory_limit'));
  30. if ($iniValue === '-1') {
  31. return -1;
  32. } elseif (is_numeric($iniValue)) {
  33. return Util::numericToNumber($iniValue);
  34. } else {
  35. return $this->memoryLimitToBytes($iniValue);
  36. }
  37. }
  38. /**
  39. * Converts the ini memory limit to bytes.
  40. *
  41. * @param string $memoryLimit The "memory_limit" ini value
  42. */
  43. private function memoryLimitToBytes(string $memoryLimit): int|float {
  44. $last = strtolower(substr($memoryLimit, -1));
  45. $number = substr($memoryLimit, 0, -1);
  46. if (is_numeric($number)) {
  47. $memoryLimit = Util::numericToNumber($number);
  48. } else {
  49. throw new \InvalidArgumentException($number.' is not a valid numeric string (in memory_limit ini directive)');
  50. }
  51. // intended fall through
  52. switch ($last) {
  53. case 'g':
  54. $memoryLimit *= 1024;
  55. // no break
  56. case 'm':
  57. $memoryLimit *= 1024;
  58. // no break
  59. case 'k':
  60. $memoryLimit *= 1024;
  61. }
  62. return $memoryLimit;
  63. }
  64. }