Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
MemoryLimit.php
Go to the documentation of this file.
1 <?php
8 namespace Magento\TestFramework;
9 
11 {
15  private $_helper;
16 
20  private $_memCap = 0;
21 
25  private $_leakCap = 0;
26 
35  public function __construct($memCap, $leakCap, \Magento\TestFramework\Helper\Memory $helper)
36  {
37  $this->_memCap = $memCap ? $helper->convertToBytes($memCap) : 0;
38  $this->_leakCap = $leakCap ? $helper->convertToBytes($leakCap) : 0;
39  $this->_helper = $helper;
40  }
41 
47  public static function printHeader()
48  {
49  return PHP_EOL . '=== Memory Usage System Stats ===' . PHP_EOL;
50  }
51 
57  public function printStats()
58  {
59  list($usage, $leak) = $this->_getUsage();
60  $result = [];
61 
62  $msg = sprintf(
63  "Memory usage (OS):\t%s (%.2F%% of %s reported by PHP",
64  $this->_toMb($usage),
65  100 * $usage / ($usage - $leak),
66  $this->_toMb($usage - $leak)
67  );
68  $percentMsg = '%.2F%% of configured %s limit';
69  if ($this->_memCap) {
70  $msg .= ', ' . sprintf($percentMsg, 100 * $usage / $this->_memCap, $this->_toMb($this->_memCap));
71  }
72  $result[] = "{$msg})";
73 
74  $msg = sprintf("Estimated memory leak:\t%s (%.2F%% of used memory", $this->_toMb($leak), 100 * $leak / $usage);
75  if ($this->_leakCap) {
76  $msg .= ', ' . sprintf($percentMsg, 100 * $leak / $this->_leakCap, $this->_toMb($this->_leakCap));
77  }
78  $result[] = "{$msg})";
79 
80  return implode(PHP_EOL, $result) . PHP_EOL;
81  }
82 
89  private function _toMb($bytes)
90  {
91  return sprintf('%.2FM', $bytes / (1024 * 1024));
92  }
93 
100  public function validateUsage()
101  {
102  if (!$this->_memCap && !$this->_leakCap) {
103  return null;
104  }
105  list($usage, $leak) = $this->_getUsage();
106  if ($this->_memCap && $usage >= $this->_memCap) {
107  throw new \LogicException(
108  "Memory limit of {$this->_toMb($this->_memCap)} ({$this->_memCap} bytes) has been reached."
109  );
110  }
111  if ($this->_leakCap && $leak >= $this->_leakCap) {
112  throw new \LogicException(
113  "Estimated memory leak limit of {$this->_toMb(
114  $this->_leakCap
115  )}" . " ({$this->_leakCap} bytes) has been reached."
116  );
117  }
118  }
119 
125  private function _getUsage()
126  {
127  $usage = $this->_helper->getRealMemoryUsage();
128  return [$usage, $usage - memory_get_usage(true)];
129  }
130 }
$helper
Definition: iframe.phtml:13
__construct($memCap, $leakCap, \Magento\TestFramework\Helper\Memory $helper)
Definition: MemoryLimit.php:35