Lines 100.00% 6 / 6
Methods 100.00% 3 / 3
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 measureResidentBytes 100.00% 2 / 2 100.00% 1 / 1 2
 readResidentPages 100.00% 3 / 3 100.00% 1 / 1 5
7final readonly class ProcessMemory
8{
9    private const string STATM = '/proc/self/statm';
10
11    public function __construct(private string $statmFile = self::STATM) {}
12
13    public function measureResidentBytes(): int
14    {
15        $residentPages = $this->readResidentPages();
16
17        return $residentPages === null ? memory_get_usage(true) : $residentPages * posix_sysconf(\POSIX_SC_PAGESIZE);
18    }
19
20    private function readResidentPages(): ?int
21    {
22        $statm = is_readable($this->statmFile) ? file_get_contents($this->statmFile) : false;
23        // The second field is the resident set size, counted in pages.
24        $residentPages = $statm === false ? null : explode(' ', trim($statm))[1] ?? null;
25
26        return $residentPages !== null && ctype_digit($residentPages) ? (int) $residentPages : null;
27    }
28}