Passed
Push — master ( bacc5f...5eccc7 )
by Dispositif
02:22
created

Memory   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
dl 0
loc 46
ccs 17
cts 17
cp 1
rs 10
c 1
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A memoryPeak() 0 5 1
A __construct() 0 2 1
A convert() 0 5 1
A memoryUsage() 0 5 1
A getMemory() 0 7 2
1
<?php
2
/**
3
 * This file is part of dispositif/wikibot application (@github)
4
 * 2019/2020 © Philippe M. <[email protected]>
5
 * For the full copyright and MIT license information, please view the license file.
6
 */
7
8
namespace App\Infrastructure;
9
10
/**
11
 * php -i | grep memory
12
 * Class Memory.
13
 */
14
class Memory
15
{
16 1
    public function __construct()
17
    {
18 1
    }
19
20
    /**
21
     * $real=true shows allocated memory (-> system monitoring)
22
     * $real=null|false shows memory used by script (-> memory leak search)
23
     * Do not take PHP external resources into account (remote/DB connection, SimpleXML, etc)
24
     * See http://drib.tech/programming/get-real-amount-memory-allocated-php.
25
     *
26
     * @param bool|null $real
27
     *
28
     * @return string
29
     * @return string
30
     */
31 1
    public function getMemory(?bool $real = null): string
32
    {
33 1
        return sprintf(
34 1
            "Memory %s: %s %s \n",
35 1
            ($real) ? '(true)' : '',
36 1
            $this->memoryUsage(),
37 1
            $this->memoryPeak()
38
        );
39
    }
40
41 1
    public function memoryUsage(?bool $real = null): string
42
    {
43 1
        $memUsage = memory_get_usage($real);
44
45 1
        return sprintf('usage: %s', $this->convert($memUsage));
46
    }
47
48 1
    public function memoryPeak(?bool $real = null): string
49
    {
50 1
        $memUsage = memory_get_peak_usage($real);
51
52 1
        return sprintf('peak: %s', $this->convert($memUsage));
53
    }
54
55 1
    private function convert(int $size): string
56
    {
57 1
        $unit = ['b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'];
58
59 1
        return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2).' '.$unit[intval($i)];
60
    }
61
}
62