1<?php declare(strict_types=1);
2
3/*
4 * This file is part of the Monolog package.
5 *
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Monolog\Processor;
13
14/**
15 * Some methods that are common for all memory processors
16 *
17 * @author Rob Jensen
18 */
19abstract class MemoryProcessor implements ProcessorInterface
20{
21    /**
22     * @var bool If true, get the real size of memory allocated from system. Else, only the memory used by emalloc() is reported.
23     */
24    protected $realUsage;
25
26    /**
27     * @var bool If true, then format memory size to human readable string (MB, KB, B depending on size)
28     */
29    protected $useFormatting;
30
31    /**
32     * @param bool $realUsage     Set this to true to get the real size of memory allocated from system.
33     * @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size)
34     */
35    public function __construct(bool $realUsage = true, bool $useFormatting = true)
36    {
37        $this->realUsage = $realUsage;
38        $this->useFormatting = $useFormatting;
39    }
40
41    /**
42     * Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is
43     *
44     * @param  int        $bytes
45     * @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as int
46     */
47    protected function formatBytes(int $bytes)
48    {
49        if (!$this->useFormatting) {
50            return $bytes;
51        }
52
53        if ($bytes > 1024 * 1024) {
54            return round($bytes / 1024 / 1024, 2).' MB';
55        } elseif ($bytes > 1024) {
56            return round($bytes / 1024, 2).' KB';
57        }
58
59        return $bytes . ' B';
60    }
61}
62