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

Memory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 0
dl 0
loc 2
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
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