summaryrefslogtreecommitdiffstats
path: root/library/Director/Application/MemoryLimit.php
blob: beb046091bd247d2b94c348afb5d81a12a2243a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

namespace Icinga\Module\Director\Application;

class MemoryLimit
{
    public static function raiseTo($string)
    {
        $current = static::getBytes();
        $desired = static::parsePhpIniByteString($string);
        if ($current !== -1 && $current < $desired) {
            ini_set('memory_limit', $string);
        }
    }

    public static function getBytes()
    {
        return static::parsePhpIniByteString((string) ini_get('memory_limit'));
    }

    /**
     * Return Bytes from PHP shorthand bytes notation
     *
     * http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
     *
     * > The available options are K (for Kilobytes), M (for Megabytes) and G
     * > (for Gigabytes), and are all case-insensitive. Anything else assumes
     * > bytes.
     *
     * @param $string
     * @return int
     */
    public static function parsePhpIniByteString($string)
    {
        $val = trim($string);

        if (preg_match('/^(\d+)([KMG])$/', $val, $m)) {
            $val = $m[1];
            switch ($m[2]) {
                case 'G':
                    $val *= 1024;
                // Intentional fall-through
                case 'M':
                    $val *= 1024;
                // Intentional fall-through
                case 'K':
                    $val *= 1024;
            }
        }

        return intval($val);
    }
}