Completed
Push — master ( bac545...383699 )
by Morris
19:54
created

MemoryInfo::getMemoryLimit()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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