PhpMemoryLimitCheck::getMegabytesFromSizeString()   B
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
eloc 12
c 1
b 0
f 1
nc 7
nop 1
dl 0
loc 17
rs 8.8333
1
<?php
2
namespace BretRZaun\StatusPage\Check;
3
4
use BretRZaun\StatusPage\Result;
5
6
class PhpMemoryLimitCheck extends AbstractCheck
7
{
8
9
    /**
10
     * @var string
11
     */
12
    protected $memoryRequired;
13
14
    /**
15
     *
16
     * @param string $label Label
17
     * @param string|int $memoryRequired amount of memory that is (at least) required in megabytes
18
     */
19
    public function __construct(string $label, $memoryRequired)
20
    {
21
        parent::__construct($label);
22
        $this->memoryRequired = $memoryRequired;
23
    }
24
25
    /**
26
     * Returns size in megabytes from a PHP size string like '1024M'.
27
     *
28
     * @param string $sizeStr
29
     * @return float|int
30
     */
31
    public function getMegabytesFromSizeString($sizeStr)
32
    {
33
        switch (substr($sizeStr, -1)) {
34
            case 'M':
35
            case 'm':
36
                return (int) $sizeStr;
37
38
            case 'K':
39
            case 'k':
40
                return (int) $sizeStr / 1024;
41
42
            case 'G':
43
            case 'g':
44
                return (int) $sizeStr * 1024;
45
46
            default:
47
                return (int) $sizeStr;
48
        }
49
    }
50
51
    /**
52
     * Check URL
53
     *
54
     * @return Result
55
     */
56
    public function checkStatus(): Result
57
    {
58
        $result = new Result($this->label);
59
        $memoryLimitString = ini_get('memory_limit');
60
        $memoryLimit = $this->getMegabytesFromSizeString($memoryLimitString);
61
62
        if ($this->memoryRequired > $memoryLimit) {
63
            $result->setError("Memory required: {$this->memoryRequired}M; limit: {$memoryLimitString}");
64
        }
65
66
        return $result;
67
    }
68
}
69