Passed
Push — master ( 732591...229bc5 )
by Dispositif
03:49
created

Memory::getMemory()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 1
nop 1
1
<?php
2
/*
3
 * This file is part of dispositif/wikibot application (@github)
4
 * 2019-2023 © Philippe M./Irønie  <[email protected]>
5
 * For the full copyright and MIT license information, view the license file.
6
 */
7
8
namespace App\Infrastructure\Monitor;
9
10
use App\Application\InfrastructurePorts\MemoryInterface;
11
12
/**
13
 * todo move /Monitor
14
 * php -i | grep memory
15
 * Class Memory.
16
 */
17
class Memory implements MemoryInterface
18
{
19
    /**
20
     * $real=true shows allocated memory (-> system monitoring)
21
     * $real=null|false shows memory used by script (-> memory leak search)
22
     * Do not take PHP external resources into account (remote/DB connection, SimpleXML, etc)
23
     * See http://drib.tech/programming/get-real-amount-memory-allocated-php.
24
     *
25
     * @param bool|null $real
26
     *
27
     * @return string
28
     * @return string
29
     */
30
    public function getMemory(?bool $real = null): string
31
    {
32
        return sprintf(
33
            "Memory %s: %s %s \n",
34
            ($real) ? '(true)' : '',
35
            $this->memoryUsage(),
36
            $this->memoryPeak()
37
        );
38
    }
39
40
    public function memoryUsage(?bool $real = null): string
41
    {
42
        $memUsage = memory_get_usage($real);
43
44
        return sprintf('usage: %s', $this->convert($memUsage));
45
    }
46
47
    public function memoryPeak(?bool $real = null): string
48
    {
49
        $memUsage = memory_get_peak_usage($real);
0 ignored issues
show
Bug introduced by
It seems like $real can also be of type null; however, parameter $real_usage of memory_get_peak_usage() does only seem to accept boolean, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

49
        $memUsage = memory_get_peak_usage(/** @scrutinizer ignore-type */ $real);
Loading history...
50
51
        return sprintf('peak: %s', $this->convert($memUsage));
52
    }
53
54
    private function convert(int $size): string
55
    {
56
        $unit = ['b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'];
57
58
        return @round($size / 1024 ** ($i = floor(log($size, 1024))), 2).' '.$unit[(int) $i];
59
    }
60
}
61