You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.2 KiB

3 years ago
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018, Michael Weimann (<mail@michael-weimann.eu>)
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Michael Weimann <mail@michael-weimann.eu>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OC;
  26. /**
  27. * Helper class that covers memory info.
  28. */
  29. class MemoryInfo {
  30. public const RECOMMENDED_MEMORY_LIMIT = 512 * 1024 * 1024;
  31. /**
  32. * Tests if the memory limit is greater or equal the recommended value.
  33. *
  34. * @return bool
  35. */
  36. public function isMemoryLimitSufficient(): bool {
  37. $memoryLimit = $this->getMemoryLimit();
  38. return $memoryLimit === -1 || $memoryLimit >= self::RECOMMENDED_MEMORY_LIMIT;
  39. }
  40. /**
  41. * Returns the php memory limit.
  42. *
  43. * @return int The memory limit in bytes.
  44. */
  45. public function getMemoryLimit(): int {
  46. $iniValue = trim(ini_get('memory_limit'));
  47. if ($iniValue === '-1') {
  48. return -1;
  49. } elseif (is_numeric($iniValue) === true) {
  50. return (int)$iniValue;
  51. } else {
  52. return $this->memoryLimitToBytes($iniValue);
  53. }
  54. }
  55. /**
  56. * Converts the ini memory limit to bytes.
  57. *
  58. * @param string $memoryLimit The "memory_limit" ini value
  59. * @return int
  60. */
  61. private function memoryLimitToBytes(string $memoryLimit): int {
  62. $last = strtolower(substr($memoryLimit, -1));
  63. $memoryLimit = (int)substr($memoryLimit, 0, -1);
  64. // intended fall trough
  65. switch ($last) {
  66. case 'g':
  67. $memoryLimit *= 1024;
  68. // no break
  69. case 'm':
  70. $memoryLimit *= 1024;
  71. // no break
  72. case 'k':
  73. $memoryLimit *= 1024;
  74. }
  75. return $memoryLimit;
  76. }
  77. }