1<?php
2
3namespace Icinga\Module\Director\Application;
4
5class MemoryLimit
6{
7    public static function raiseTo($string)
8    {
9        $current = static::getBytes();
10        $desired = static::parsePhpIniByteString($string);
11        if ($current !== -1 && $current < $desired) {
12            ini_set('memory_limit', $string);
13        }
14    }
15
16    public static function getBytes()
17    {
18        return static::parsePhpIniByteString((string) ini_get('memory_limit'));
19    }
20
21    /**
22     * Return Bytes from PHP shorthand bytes notation
23     *
24     * http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
25     *
26     * > The available options are K (for Kilobytes), M (for Megabytes) and G
27     * > (for Gigabytes), and are all case-insensitive. Anything else assumes
28     * > bytes.
29     *
30     * @param $string
31     * @return int
32     */
33    public static function parsePhpIniByteString($string)
34    {
35        $val = trim($string);
36
37        if (preg_match('/^(\d+)([KMG])$/', $val, $m)) {
38            $val = $m[1];
39            switch ($m[2]) {
40                case 'G':
41                    $val *= 1024;
42                // Intentional fall-through
43                case 'M':
44                    $val *= 1024;
45                // Intentional fall-through
46                case 'K':
47                    $val *= 1024;
48            }
49        }
50
51        return intval($val);
52    }
53}
54